繁体   English   中英

如何将事件处理程序绑定/添加到 Datagrid MVVM?

[英]How to bind/add event handler to Datagrid MVVM?

我想让消息框在用户按下删除按钮删除 MVVM 模型中数据网格中的行时出现。 我发现可以像这样捕获删除事件:

    <DataGrid CommandManager.PreviewCanExecute="Grid_PreviewCanExecute" />
private void Grid_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
  DataGrid grid = (DataGrid)sender;
  if (e.Command == DataGrid.DeleteCommand)
  {
    if (MessageBox.Show(String.Format("Would you like to delete {0}", (grid.SelectedItem as Person).FirstName), "Confirm Delete", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
      e.Handled = true;
  }
}

我想问一下在mvvm模型中如何做到这一点? 谢谢

您可以使用以下代码在触发特定事件时执行方法(订阅事件)。

yourElement.yourEvent += theMethodToExecute;

您要调用的方法必须具有与事件“输出/返回”相同的参数。

Event<string> yourEvent; // Event that contains string value

theMethodToExecute(string eventData) {}  // must expect string value

希望这可以帮助你!

你可以做类似的事情

首先绑定到一个键

    <Grid>
    .... 
         <DataGrid.InputBindings>
             <KeyBinding  Key="Delete" Command="{Binding DeleteCommand, Mode=OneWay}"  CommandParameter="{Binding Path=SelectedItem, ElementName=yourElementName, Mode=OneWay}"/>
         </DataGrid.InputBindings>
    ....
    </Grid>

其次,在您的视图模型中创建一个命令

 public RelayCommand DeleteCommand { get; set; }
 DeleteCommand = new RelayCommand(execute, canExecute);

现在您可以使用您之前为 canExecute 编写的相同函数,并进行一些小调整

private void canExecute (object SelectedItem)
{
   if(...)
     return true
   else(...)
     return false 
}

编辑

你可以使用像Prism这样的 MVVM 库,这会让你的生活更轻松

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM