【问题标题】:How to bind/add event handler to Datagrid MVVM?如何将事件处理程序绑定/添加到 Datagrid MVVM?
【发布时间】:2020-02-04 08:07:16
【问题描述】:

我想让消息框在用户按下删除按钮删除 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模型中如何做到这一点?谢谢

【问题讨论】:

标签: c# wpf mvvm datagrid


【解决方案1】:

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

yourElement.yourEvent += theMethodToExecute;

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

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

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

希望对您有所帮助!

【讨论】:

    【解决方案2】:

    你可以做类似的事情

    首先绑定到一个键

        <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 库,这将使您的生活更轻松

    【讨论】:

      猜你喜欢
      • 2011-11-11
      • 1970-01-01
      • 2011-10-11
      • 2021-02-26
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多