簡體   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