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

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

问题描述

我正在使用 MVVM 模式、RelayCommand 等开发 WPF 应用程序.我在这个问题上读了很多,但我不清楚:

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.

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

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.

解决方案?

推荐答案

在编写 MVVM 图形应用程序时,很容易尝试将您需要的所有事件发送到视图模型.但是在命令中处理特定于视图的鼠标事件参数有悖于 MVVM 原则和松耦合的目标.

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.

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

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天全站免登陆