WPF – Handling events from user control in View Model

eventsmvvmwpf

I’m building a WPF application using MVVM pattern (both are new technologies for me). I use user controls for simple bits of reusable functionality that doesn’t contain business logic, and MVVM pattern to build application logic. Suppose a view contains my user control that fires events, and I want to add an event handler to that event. That event handler should be in the view model of the view, because it contains business logic. The question is – view and the view model are connected only by binding; how do I connect an event handler using binding? Is it even possible (I suspect not)? If not – how should I handle events from a control in the view model? Maybe I should use commands or INotifyPropertyChanged?

Best Answer

Generally speaking, it is a good MVVM-practice to avoid code in code behind, as would be the case if you use events in your user controls. So when possible, use INotifyPropertyChanged and ICommand.

With that said, depending on your project and how pragmatic you are, some times it makes more sense to use the control's code behind.

I have at a few occasions used something like this:

private void textBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    MyViewModel vm = this.DataContext as MyViewModel;
    vm.MethodToExecute(...);
}

You could also consider Attached Command Behaviour, more info about this and implementations to find here:

Firing a double click event from a WPF ListView item using MVVM