WPF和MVVM。结合事件 [英] WPF and MVVM. Binding Events

查看:428
本文介绍了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.

要解决这个问题的方法是抽象操作进入该视图可以执行,然后进行通信的结果反馈给通过操作和数据的视图模型的任务。如果你想在code-后面执行code少量支持这一点,MVVM警方不会来照顾你的孩子。但更好的方法是用行为增加互动性。行为是可重复使用的功能件,没有code-身后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:

  • 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.

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

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