[英]How to bind/add event handler to Datagrid MVVM?
i want to make message box to appear when user press delete button to delete row in datagrid in MVVM model.我想让消息框在用户按下删除按钮删除 MVVM 模型中数据网格中的行时出现。 I found that delete event can be catch like this:我发现可以像这样捕获删除事件:
<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;
}
}
I would like to ask how to do that in mvvm model?我想问一下在mvvm模型中如何做到这一点? Thank you谢谢
You can use following code to execute a method when a specific event gets fired (Subscribing to an event).您可以使用以下代码在触发特定事件时执行方法(订阅事件)。
yourElement.yourEvent += theMethodToExecute;
The method you want to call has to have the same parameters as the event "outputs/returns".您要调用的方法必须具有与事件“输出/返回”相同的参数。
Event<string> yourEvent; // Event that contains string value
theMethodToExecute(string eventData) {} // must expect string value
Hope this could help you!希望这可以帮助你!
You can do something like你可以做类似的事情
first bind to a key首先绑定到一个键
<Grid>
....
<DataGrid.InputBindings>
<KeyBinding Key="Delete" Command="{Binding DeleteCommand, Mode=OneWay}" CommandParameter="{Binding Path=SelectedItem, ElementName=yourElementName, Mode=OneWay}"/>
</DataGrid.InputBindings>
....
</Grid>
second, create a command in your view model其次,在您的视图模型中创建一个命令
public RelayCommand DeleteCommand { get; set; }
DeleteCommand = new RelayCommand(execute, canExecute);
and now you can use the same function you wrote before for canExecute with some minor tweaks现在您可以使用您之前为 canExecute 编写的相同函数,并进行一些小调整
private void canExecute (object SelectedItem)
{
if(...)
return true
else(...)
return false
}
Edit编辑
you can use MVVM library like Prism that will make your life much easier你可以使用像Prism这样的 MVVM 库,这会让你的生活更轻松
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.