简体   繁体   中英

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. 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? 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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