How can I handle delegates in my view model?

Viewed 27

I use the code below to handle row clicks in Telerik GridView, how can I handle the delegate for this method in my view model instead of handling OnRowMouseDown in my view?

EventManager.RegisterClassHandler(typeof(GridViewRow), GridViewRow.MouseLeftButtonDownEvent, new RoutedEventHandler(OnRowMouseDown), true);

The parameter new RoutedEventHandler(OnRowMouseDown) is a delegate.

1 Answers

You must handle the actual event using an event handler with a specific signature.

What you can do is to call a method of your view model from the event handler, i.e. in OnRowMouseDown:

var viewModel = DataContext as YourViewModel;
viewModel.SomeMethod();

The call to EventManager.RegisterClassHandler(typeof(GridViewRow), GridViewRow.MouseLeftButtonDownEvent, new RoutedEventHandler(OnRowMouseDown), true); in the view stays the same and so does the signature of OnRowMouseDown. You just move the logic from the event handler to the view model. This is what MVVM is all about basically.

Related