2015-09-27 124 views
0

我是MVVMCross的新手。我正在通过继承MVXTableVIewCell创建一个自定义表格视图单元格。我在单元格中有一个删除按钮。当用户点击删除按钮时,相同的记录将从表中删除。我不知道如何将存在于我的单元格中的删除按钮绑定到视图模型类。下面显示的是ViewModel类,自定义单元类和RelayCommand类。Xamarin MVVMCross绑定MVXtableViewCell

public class DebriefViewModel: MvxViewModel, INotifyPropertyChanged 
{ 
    public RelayCommand DeleteDebriefCommand { get; set; } 
    public DebriefViewModel() 
    { 
    DeleteDebriefCommand = new RelayCommand(DoDeleteDebrief); 
    } 
    public async void DoDeleteDebrief(object param) 
    { 
     Debrief debriefDelete = (Debrief)param; 
    //Code to delete the debrief. 
    } 
} 

public partial class DebriefViewCell : MvxTableViewCell 
{ 
    public static readonly UINib Nib = UINib.FromName("DebriefViewCell", NSBundle.MainBundle); 
    public static readonly NSString Key = new NSString ("DebriefViewCell"); 

    public DebriefViewCell (IntPtr handle) : base(BindingText,handle) 
    { 
     this.DelayBind(() => { 
      var set = this.CreateBindingSet<DebriefViewCell, DebriefViewModel>(); 
      //Not sure how to bind the deleteDebriefBttn 
      set.Bind(deleteDebriefBttn).To(vm => vm.DeleteDebriefCommand); 
      set.Apply(); 
     }); 
    } 

    public static DebriefViewCell Create() 
    { 
     return (DebriefViewCell)Nib.Instantiate (null, null) [0]; 
    } 
} 

public class RelayCommand : ICommand 
{ 
    // Event that fires when the enabled/disabled state of the cmd changes 
    public event EventHandler CanExecuteChanged; 

    // Delegate for method to call when the cmd needs to be executed   
    private readonly Action<object> _targetExecuteMethod; 

    // Delegate for method that determines if cmd is enabled/disabled   
    private readonly Predicate<object> _targetCanExecuteMethod; 

    public bool CanExecute(object parameter) 
    { 
     return _targetCanExecuteMethod == null || _targetCanExecuteMethod(parameter); 
    } 

    public void Execute(object parameter) 
    { 
     // Call the delegate if it's not null 
     if (_targetExecuteMethod != null) _targetExecuteMethod(parameter); 
    } 

    public RelayCommand(Action<object> executeMethod, Predicate<object> canExecuteMethod = null) 
    { 
     _targetExecuteMethod = executeMethod; 
     _targetCanExecuteMethod = canExecuteMethod; 
    } 

    public void RaiseCanExecuteChanged() 
    { 
     if (CanExecuteChanged != null) CanExecuteChanged(this, EventArgs.Empty); 
    } 
} 

我不知道如何绑定“deleteDebriefBttn”出现在我的DebriefViewCell到DeleteDebriefCommand存在于DebriefViewModel的。请帮帮我。

回答

1

在TableSource构造函数中传递ViewModel引用,然后在CommitEditingStyle覆盖中使用此ViewModel的Command。

public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) 
     { 
      switch (editingStyle) 
      { 
       case UITableViewCellEditingStyle.Delete: 
        viewModel.RemoveCommand.Execute(indexPath.Row); 
        break; 
      } 
     }