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?
+2
A:
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
Tendlon
2010-05-28 07:06:51
Control should be reusable, so the code won't do - it ties the control to a specific view model. Commands... Probably not - they are more for user actions. INotifyPropertyChanged then?Thanks :)
Vitaly
2010-05-28 07:11:08
Hard to say for me without knowing more specifics. But I added in some links to related info
Tendlon
2010-05-28 07:19:54
@Vitaly if you are worried about tying the View to the explicit ViewModel, you could wrap the ViewModel in an interface. I would look into Attached Command Behaviors they are becoming the accepted practice. Also, check out MVVMLight or Caliburn as a framework to assist in your MVVM work, it will make you life much easier.
Agies
2010-05-29 01:50:32
+1
A:
Also take a look at question http://stackoverflow.com/questions/2682273/how-can-i-add-a-new-command-to-a-controls-event/2682422
Daniel Rose
2010-05-28 07:25:19