MVVM与事件处理程序

MVVM与事件处理程序

本文介绍了使用命令的WPF MVVM与事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢MVVM模式,一旦开始使用它,就会迷上它.

I like MVVM pattern, once you start using it, you get addicted to it.

我知道,在理想情况下,您的View背后代码几乎是空的(可能是构造函数中的某些代码),并且View的每个方面都可以通过ViewModel进行操作.

I know that in perfect world your View code-behind is almost empty (maybe some code in constructor) and every aspect of View is being manipulated from ViewModel.

但是有时候在ViewModel中创建新的字段,属性和命令所创建的代码要比在事件处理程序中实现相同的东西更多.

But there are times when creating new fields, properties,commands in ViewModel creates more code than implementing same thing in event handler.

此刻,我遵循以下规则:

At moment I stick to following rule:

如果事件处理程序代码操纵了视图的很小一部分(例如,按钮单击事件处理程序增加了位于同一视图上的某些TextBlock的字体),那么可以在事件处理程序内实现逻辑.但是,如果View需要操纵业务逻辑或访问View之外的资源,那么我将这些职责分配给ViewModel.

If event handler code manipulates very small portion of it's view (for example button click event handler increases font of certain TextBlock that's located on the same view) then it's OK to implement logic inside event handlers. But if View needs to manipulate business logic or access resources that are outside of view, then I assign these responsibilities to ViewModel.

您如何看待我的方法?

What do You think about my approach?

使用事件处理程序和ViewModel时要避免什么?

What do You try to avoid when using event handlers and ViewModel?

使用MVVM模式时,您可以推荐哪些最佳实践?

What best practices can You recommend when using MVVM pattern?

推荐答案

我会说你的经验法则还不错.

I'd say your rule of thumb is not bad.

在我看来,核心问题是代码是特定于视图的,还是针对业务逻辑?".

In my view, the core concern is "is the code view-specific, or does it address business logic?".

在视图中有代码是可以的,如果严格在这里修改视图而不执行任何业务逻辑的代码.您更改字体大小的示例是一个代码示例,它在视图中非常好(并且会增加ViewModel中的干扰,使其更难于理解和维护).从本质上讲,如果使用触发器,您已经做过一些事情,所以并不是那么奇怪.

It is OK to have code in the view, if that code is strictly here to modify the view and not to carry out any kind of business logic. Your example of changing a font size is a prime example of code that is perfectly fine in a view (and would increase noise in a ViewModel, making it harder to understand and maintain).In essence, you already do some of that if you use triggers, so it's not that weird.

但是请记住,如果您使用单元测试,那么很难测试一下视图逻辑.如果需要对其进行测试,则最好将其放入视图模型中.

Keep in mind though, if you use unit tests, it will be very difficult to test that bit of view-logic. If you need it tested, you might be better off putting it in the viewmodel.

这篇关于使用命令的WPF MVVM与事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:04