MVVMCross Fragment 和动态设置事件命令

MVVMCross Fragment and dynamically setting event commands

我有一个绑定到定义了两个 ICommand 属性的视图模型的 MvxFragment。此片段包含一个 MvxListView,并且可以是不同 activities/layouts 的一部分,具体取决于设备 size/orientation。

我想知道的是如何动态指定MvxListView的MvxBind属性的ItemClick事件命令,或者有更好的方法来处理这个用例吗?我应该使用单独的片段吗?

Xamarin Dev Guide

的概述部分中有一个与我试图实现的类似用例

查看

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <MvxListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        local:MvxBind="ItemsSource Courses; ItemClick Comamnd1"
        local:MvxItemTemplate="@layout/coursetemplate" />
</LinearLayout>

ViewModel(简体)

public class MyViewModel : MvxViewModel
{
    private MvxCommand<MyMessage> messageCommand;

    public MyViewModel (IMvxMessenger messenger, IHttpClientBuilderService httpClientBuilder)
    {
        this.httpClientBuilder = httpClientBuilder;
        this.messenger = messenger; 
    }

    public ICommand Comamnd1 {
        get { return new MvxCommand<Course> ((c) => ShowViewModel<MyOtherViewModel>(c)); }
    }

    public ICommand Command2 {
        get 
        { 
            messageCommand = messageCommand ?? new MvxCommand<MyMessage>(c => 
                {
                    var message = new MyMessage(this, c);
                    messenger.Publish(message);                     
                }); 
            return selectedCourse;
        }
    }

}

好的,您可以通过覆盖片段的 OnActivityCreated 事件来执行此操作,如下所示。

    public override void OnActivityCreated (Bundle savedInstanceState)
    {
        base.OnActivityCreated (savedInstanceState);

        MvxListView list = Activity.FindViewById<MvxListView>(Resource.Id.[theID]);

        if (Activity.FindViewById<View>(Resource.Id.[fragmentID]) != null)
            list.ItemClick = ((MyViewModel)ViewModel).Command1;
        else
            list.ItemClick = ((MyViewModel)ViewModel).Command2;
    }

您可以使用 Activity.FindViewById 函数拉出列表,然后通过 list.ItemClick 事件[=16] 从 ViewModel 中设置适当的 ICommandIMvxCommand =]