2017-02-24 45 views
1

我有具有以下axml文件MvxRecyclerView:如何连接起来MvxRecyclerView项目的行动视图模型

<?xml version="1.0" encoding="utf-8"?> 
<MvvmCross.Droid.Support.V7.RecyclerView.MvxRecyclerView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:MvxItemTemplate="@layout/item_detail" 
    app:MvxBind="ItemsSource Items" /> 

Correspodning视图模型的定义是这样的:

public class ItemsViewModel : MvxViewModel 
{ 
    private ObservableCollection<Models.Item> _items; 

    public ObservableCollection<Models.Item> Items 
    { 
     get { return _items; } 
     set 
     { 
      _items = value; 
      RaisePropertyChanged(() => Items); 
     } 
    } 

    public MvxCommand CommandToBeInvokedFromItem 
    { 
     get 
     { 
      return new MvxCommand(async() => 
      { 
       await ...; 
      }); 
     } 
    } 
    ... 
} 

我item_detail axml的定义如下这个:

<?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:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 

    <TextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"   
    android:textSize="24dp" 
    local:MvxBind="Text Name" /> 

    <ImageButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/ic_delete_forever_black_24dp" 
    local:MvxBind="Click CommandToBeInvokedFromItem"/> 

</LinearLayout> 

而Model.Item是这样定义的:

public class Item 
{ 
    public string Name { get; set; } 
} 

第一个TextView绑定到项目的名称属性,它很好用。但是我希望ImageButton绑定到绑定了MvxRecylerView的ViewModel上的Command,而不是Item的属性。 Item只是一个Model而不是ViewModel。我如何实现这一目标?

回答

0

如果您需要点击MvxRecycler(即整个单元格)中的项目来调用该命令,则绑定相对简单。只需将MvxRecyclerView上的MvxBind的值从ItemsSource Items更改为ItemsSource Items; ItemClick CommandToBeInvokedFromItem即可。然后CommandToBeInvokedFromItem将需要被修改以接受Item作为一种类型的参数,这将是这样的:

public MvxCommand<Models.Item> CommandToBeInvokedFromItem 
{ 
    get 
    { 
     return new MvxCommand<Models.Item>(async() => 
     { 
      await ...; 
     }); 
    } 
} 

如果命令需要被通过单击ImageButton特别提出,则最简单的方法是移动CommandToBeInvokedFromItemItem,并使物品继承MvxViewModel,或者至少实现INotifyPropertyChanged

+0

卢克,谢谢,但这是我所渴望的第二种行为。我想连接命令以点击位于MvxRecyclerView“单元格”内的ImageButton。是的,我想知道如果我可以做到这一点,没有Item从MvxViewModel继承。 – Igor

+0

它应该正常工作,而不会继承'MvxViewModel'。只需将'CommandToBeInvokedFromItem'移动到'Item'。 –

0

当您在ItemsViewModel中创建该命令时,将命令转交给Item

public class Item 
{ 
    public string Name { get; set; }   
    public MvxCommand CommandToBeInvokedFromItem {get;} 

    public Item(MvxCommand clickCommand) 
    { 
     CommandToBeInvokedFromItem = clickCommand; 
    } 
} 
相关问题