WPF and MVVM. Binding Events

Dani O. picture Dani O. · Jan 24, 2011 · Viewed 14.4k times · Source

I'm developing a WPF application with the MVVM pattern, RelayCommand, etc. I read a lot on this question but I am not clear as to:

All I want to do is move a shape, like an ellipse, for example, and capture its final position, to put in the database.

But I can't bind events (MouseLetButtonDown, MouseLeftButtonUp and MouseMove) to commands. I've read about attached behaviours , but I need the arguments of the events (MouseButtonEventArgs and MouseEventArgs) to retrieve the position.

Solution?

Answer

Rick Sladkey picture Rick Sladkey · Jan 24, 2011

When writing an MVVM graphical application, it is tempting to try to send all the events you need over to the view-model. But processing view-specific mouse event args in a command is contrary to MVVM principles and the goal of loose-coupling.

The way to solve this problem is to abstract the operation into a task that the view can perform and then to communicate its results back to the view-model via operations and data. If you want to perform a small amount of code in the code-behind to support this, the MVVM police will not come and take your children. But an even better way is to add interactivity with behaviors. Behaviors are re-usable pieces of functionality with no code-behind that work well with the MVVM pattern and applications that need interactivity that would otherwise require adding event handlers to your XAML.

See my answer here for a complete example of a behavior that uses mouse events for dragging graphical objects:

With your interactivity performed by the view, the view-model can stick to data and commands.