MVVMCross Fragment和动态设置事件命令

时间:2015-12-09 15:33:21

标签: android-fragments xamarin mvvmcross

我有一个绑定到视图模型的MvxFragment,它定义了两个ICommand属性。此片段包含一个MvxListView,可以是不同活动/布局的一部分,具体取决于设备大小/方向。

我想知道的是如何动态指定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(Simpified)

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;
        }
    }

}

1 个答案:

答案 0 :(得分:1)

好的,你可以这样做,重写片段的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功能提取列表,然后通过ICommand事件

从ViewModel设置适当的IMvxCommandlist.ItemClick