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?
Asked
Active
Viewed 2.9k times
1 Answers
20
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

Richard Garside
- 87,839
- 11
- 80
- 93

ThomasAndersson
- 1,844
- 12
- 23
-
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 May 28 '10 at 07:11
-
Hard to say for me without knowing more specifics. But I added in some links to related info – ThomasAndersson May 28 '10 at 07:19
-
@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 May 29 '10 at 01:50
-
Sorry for Necro-Threading but I've been fiddling with trying to get my events handled in my controller for awhile and at the line of which I call the function I get "System.NullReferenceException" from which I assume DataContext is empty and is trying to build my controller? – J. Scull Jul 13 '17 at 14:01
-
Would `((TypeOfControl)sender).DataContext` be an option to do it for individual controls and also to avoid cases where the `DataContext` is not directly in the window? – Daniel Möller Jun 27 '20 at 14:49