【问题标题】:How can I attach a MvxCommand to a BottomBar?如何将 MvxCommand 附加到 BottomBar?
【发布时间】:2017-07-10 18:53:31
【问题描述】:

我正在使用this 库将BottomNavigationBar 添加到我的项目中。我也在为我的这个项目的框架使用 MvvmCross。我不知道如何将MvxCommand 绑定到我的BottomBar。有谁知道如何做到这一点?

这大概是我在ViewModel 中的MvxCommand 的样子:

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

我的BottomBar 创作如下:

    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
    }

【问题讨论】:

  • 在视图的“OnMenuTabSelected”方法中添加“if (menuItemId == xxx) myViewModel.OnTabSelectedCommand.Execute()”。
  • @hugo 它不想工作。我打电话给ListHomeViewModel.OnTabSelectedCommand.Execute();,但这会导致错误。我需要发出命令static吗?
  • 不,如果你使用这样的声明“public class myview : MvxActivity”,你将拥有一个名为“ViewModel”的属性,它的类型是“MyViewModel”。然后你需要调用“ViewModel.OnTabSelectedCommand.Execute()”。对不起,错误的视图模型使用...
  • @hugo 现在可以使用了!谢谢你。如果你想写一个答案,我会把它标记为正确的。

标签: c# xamarin mvvm xamarin.android mvvmcross


【解决方案1】:

如果你这样声明你的活动:

public class MyView : MvxActivity<MyViewModel>

您将能够访问类型为“MyViewModel”的属性“ViewModel”。

然后你只需要调用你的命令:

ViewModel.OnTabSelectedCommand.Execute();

此调用应包含在您的切换命令中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2020-05-27
    • 2015-11-12
    • 2017-05-10
    • 2011-08-10
    • 2014-01-31
    相关资源
    最近更新 更多