tags:

views:

280

answers:

2

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
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
Hard to say for me without knowing more specifics. But I added in some links to related info
Tendlon
@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