Search code examples
c#xamarinmvvmxamarin.androidmvvmcross

How can I attach a MvxCommand to a BottomBar?


I am using this library to add a BottomNavigationBar to my project. I am also using MvvmCross for my framework for this project. I cannot figure out how to bind a MvxCommand to my BottomBar though. Does anyone know how this could be done?

Here is roughly what my MvxCommand in the ViewModel looks like:

public ICommand OnTabSelectedCommand 
{
    get { return New MvxCommand(() => OnTabSelected()); }
}

My BottomBar creation looks like this:

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        var recycler = FindViewById<MvxRecyclerView>(Resource.Id.menuList);
        var layoutManager = new LinearLayoutManager(this);
        recycler.SetLayoutManager(layoutManager);
        recycler.NestedScrollingEnabled = false;


        var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbarFinder);
        SetSupportActionBar(toolbar);

        _bottomBar = BottomBar.AttachShy((CoordinatorLayout)FindViewById(Resource.Id.ListCoordinator),
                         FindViewById(Resource.Id.menuList), savedInstanceState);

        _bottomBar.SetItems(new[]
              { new BottomBarTab(Resource.Drawable.ic_recents, "Recents"),
                new BottomBarTab(Resource.Drawable.ic_favorites, "Favorites"),
                new BottomBarTab(Resource.Drawable.ic_nearby, "Nearby") }
            );

        _bottomBar.SetOnMenuTabClickListener(this);

        _bottomBar.SetActiveTabColor(Color.Red);

        _bottomBar.MapColorForTab(0, "#7B1FA2");
        _bottomBar.MapColorForTab(1, "#FF5252");
        _bottomBar.MapColorForTab(2, "#FF9800");
    }

    public void OnMenuTabSelected(int menuItemId)
    {
        // Do something
    }

    public void OnMenuTabReSelected(int menuItemId)
    {
        // Do Something
    }

Solution

  • If you declare your Activity like this:

    public class MyView : MvxActivity<MyViewModel>
    

    You will be able to access the property "ViewModel" which is of type "MyViewModel".

    Then you just need to call your command with:

    ViewModel.OnTabSelectedCommand.Execute();
    

    This call should be included with a switch command in your:

    public void OnMenuTabSelected(int menuItemId)
    {
        // Do something
    }