Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF and MVVM. Binding Events

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?

like image 349
Dani O. Avatar asked Jan 24 '11 18:01

Dani O.


People also ask

How many types of binding are there in WPF?

WPF binding offers four types of Binding. Remember, Binding runs on UI thread unless otherwise you specify it to run otherwise.

Does WPF use MVVM?

MVVM is the lingua franca of WPF developers because it is well suited to the WPF platform, and WPF was designed to make it easy to build applications using the MVVM pattern (amongst others).

What is WPF data binding?

Data binding in Windows Presentation Foundation (WPF) provides a simple and consistent way for apps to present and interact with data. Elements can be bound to data from different kinds of data sources in the form of . NET objects and XML.


2 Answers

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:

  • Coach a newbie through basic WPF? (I Do Not Grok It.)

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

like image 138
Rick Sladkey Avatar answered Sep 28 '22 09:09

Rick Sladkey


This works for Silverlight so it should work on WPF (or at least it should with minor modifications)

<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<cmd:EventToCommand Command="{Binding MouseCommand, PassEventArgsToCommand="True", CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
like image 23
paxx Avatar answered Sep 28 '22 10:09

paxx