WPF和MVVM。绑定事件 [英] WPF and MVVM. Binding Events

查看:791
本文介绍了WPF和MVVM。绑定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发具有MVVM模式的WPF应用程序,RelayCommand等。
我在这个问题上阅读了很多,但我不清楚:



所有我想要做的就是移动像椭圆一样的形状,并且捕获其最终位置,放入数据库。



但是我可以将事件(MouseLetButtonDown,MouseLeftButtonUp和MouseMove)绑定到命令。我已经阅读了附加的行为,但我需要事件的参数(MouseButtonEventArgs和MouseEventArgs)来检索位置。



解决方案?

解决方案

在编写MVVM图形应用程序时,尝试将所需的所有事件发送到视图模型是很诱人的。但是,在命令中处理视图特定的鼠标事件参数与MVVM原理和松耦合的目标是相反的。



解决这个问题的方法是抽象操作进入视图可以执行的任务,然后通过操作和数据将其结果传回给视图模型。如果您想在代码隐藏中执行少量代码来支持这一点,那么MVVM警察将不会来带你的孩子。但更好的方法是增加交互性与行为。行为是可重用的功能部分,没有代码隐藏,与需要交互性的MVVM模式和应用程序一起工作,否则需要向XAML添加事件处理程序。



请参阅我的答案,了解一个使用鼠标事件拖动图形对象的行为的完整示例:





由视图执行的交互性,视图模型可以坚持数据和命令。


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?

解决方案

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.

这篇关于WPF和MVVM。绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆