9

我是 WPF MVVM 的新手 .. 有人清楚 WPF 中 MVVM 应用程序中行为的用法吗?为什么即使我们在 WPF MVVM 中有 Method 操作,我们也应该选择 Behavior ?

4

3 回答 3

6

行为是您附加到元素的东西,并指定应用程序应何时响应。

Action 附加到行为上,并定义了当行为被触发时应用程序应该做什么。

从这篇文章:

乍一看,一个行为看起来类似于一个动作:一个独立的功能单元。主要区别在于动作期望被调用,并且当被调用时,它们将执行一些操作。一个行为没有调用的概念;相反,它更多地充当对象的附加组件:如果需要,可以附加到对象的可选功能。它可能会响应来自环境的刺激做某些事情,但不能保证用户可以控制这个刺激是什么:由行为作者决定什么可以定制,什么不能定制。

从这篇文章中

行为让您可以将多个相关或依赖的活动以及状态封装在一个可重用的单元中。

于 2012-05-21T10:27:39.983 回答
2

我强烈推荐阅读WPF 中的附加行为简介,它演示了:

  • 什么是依附行为
  • 它有什么替代品
  • 与类似问题的替代解决方案相比,它的优势

这个想法是您在元素上设置附加属性,以便您可以从公开附加属性的类中访问该元素。一旦该类可以访问该元素,它就可以在其上挂钩事件,并响应这些事件触发,使该元素执行它通常不会执行的操作。它是创建和使用子类的一种非常方便的替代方法,并且对 XAML 非常友好。

上述文章的结论:

Hooking an event on an object and doing something when it fires is certainly not a breakthrough innovation, by any stretch of the imagination. In that sense, attached behaviors are just another way to do the same old thing. However, the importance of this technique is that it has a name, which is probably the most important aspect of any design pattern. In addition, you can create attached behaviors and apply them to any element without having to modify any other part of the system. It is a clean solution to the problem raised by Pascal Binggeli, and many, many other problems. It's a very useful tool to have in your toolbox.

于 2015-02-19T09:32:37.177 回答
0

在 MVVM 中,如果您的 ViewModel 公开方法而不是命令,您可能需要从视图中调用方法。行为允许这样做。

您声明“我们在 WPF MVVM 中有方法操作”,但据我所知,“方法操作”不是 WPF 的一部分。如果您使用的是辅助 MVVM 库,它可能会提供可以将方法封装在命令中的“方法操作”。在这种情况下,使用方法的 MVVM 模式不需要行为。

但请注意,这些行为在 MVVM 之外还有其他用途。

于 2012-08-07T12:04:06.410 回答