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?
WPF binding offers four types of Binding. Remember, Binding runs on UI thread unless otherwise you specify it to run otherwise.
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).
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With