Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Handling events from user control in View Model

Tags:

events

mvvm

wpf

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?

like image 441
Vitaly Avatar asked May 28 '10 06:05

Vitaly


People also ask

What is the difference between UserControl and window in WPF?

A window is managed by the OS and is placed on the desktop. A UserControl is managed by wpf and is placed in a Window or in another UserControl. Applcations could be created by have a single Window and displaying lots of UserControls in that Window.

What is UserControl WPF?

User controls, in WPF represented by the UserControl class, is the concept of grouping markup and code into a reusable container, so that the same interface, with the same functionality, can be used in several different places and even across several applications.


1 Answers

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

like image 96
ThomasAndersson Avatar answered Sep 20 '22 15:09

ThomasAndersson