在 MVVM 中,ViewModel 响应 View 中用户操作的最佳方式是什么? [英] In MVVM, what is the best way for the ViewModel to respond to user actions in the View?
问题描述
我明白在 MVVM 中:
I understand that in MVVM:
- View 知道 ViewModel
- ViewModel 知道模型
- 但它不能向上工作,所以模型对 ViewModel 一无所知
- ViewModel 对 View 一无所知
那么ViewModel 如何响应用户在 View 上执行的操作,例如在 TextBox 中输入内容或移动滑块等.
So how does the ViewModel respond to actions that the user does on the View, e.g. type something into a TextBox or move a slider, etc.
我知道这是通过 RoutedEvents 完成的,但我发现几乎所有 RoutedEvent 示例都在视图中使用 CodeBehind,而这正是 MVVM 中所没有的.
I understand that this is done with RoutedEvents but almost all RoutedEvent examples I find use CodeBehind in the View, which is exactly what you don't have anymore in MVVM.
这样就剩下 RoutedCommands,我在 MVVM 中找到了更多示例,但例如从这个意义上说,移动滑块实际上不是命令,而是一个事件,所以我想知道这是否真的应该使用.
So that leaves RoutedCommands which I find more examples of in MVVM but e.g. moving a slider really isn't a command in that sense, it is an event, so I am wondering if this is really what should be used.
然后我 阅读建议,例如在 MVVM 中尽可能少地使用 RoutedEvents,并且根本不使用 RoutedCommands.".
Then I read advice such as "In MVVM use RoutedEvents as little as possible, and no RoutedCommands at all." OK.
这样就离开了,例如在 WPF 模型视图中-ViewModel Toolkit 0.1 项目由 WPF 团队自己组成,您有一个DelegateCommand",这看起来也很有趣.
So that leaves, e.g. in the WPF Model-View-ViewModel Toolkit 0.1 project form the WPF team themselves you have a "DelegateCommand" which also looks like an interesting way.
然后有些人也在使用RelayCommand".
Then some people are also using "RelayCommand".
对于开发应用程序如此核心的事情来说,这是很多选择和困惑.
This is a lot of choices and confusion for doing something so core to developing applications.
在 MVVM 中简单地完成过去 10 年我们使用代码隐藏所做的事情的最佳方法是什么:
- 创建按钮
- 双击按钮
- 编写处理代码
推荐答案
澄清一下,当人们提到 DelegateCommand 和 RelayCommand 时,他们实际上是在谈论同一个事物:ICommand 的一个实现,它允许您传入一个委托.您可以交替使用它们.
Just to be clear, when people mention DelegateCommand and RelayCommand, they are really talking about the same thing: an implementation of ICommand that allows you to pass in a delegate. You can use them interchangeably.
就我而言,将视图 (XAML) 绑定到 ViewModel 中的 DelegateCommands 是实现 MVVM 的最佳方式.
As far as I am concerned, having your view (XAML) bind to DelegateCommands in the ViewModel is the best way to implement MVVM.
我尽可能远离 RoutedEvents 和代码隐藏.
I stay away from RoutedEvents AND code-behind whenever possible.
这篇关于在 MVVM 中,ViewModel 响应 View 中用户操作的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!