WPF - 在视图模型中处理来自用户控件的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2927153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF - Handling events from user control in View Model
提问by Vitaly
I'm building a WPF application using MVVM pattern (both are new technologies for me). I use user controls for simple bits of reusable functionality that doesn't contain business logic, and MVVM pattern to build application logic. Suppose a view contains my user control that fires events, and I want to add an event handler to that event. That event handler should be in the view model of the view, because it contains business logic. The question is – view and the view model are connected only by binding; how do I connect an event handler using binding? Is it even possible (I suspect not)? If not – how should I handle events from a control in the view model? Maybe I should use commands or INotifyPropertyChanged?
我正在使用 MVVM 模式构建 WPF 应用程序(这两种技术对我来说都是新技术)。我将用户控件用于不包含业务逻辑的可重用功能的简单位,并使用 MVVM 模式来构建应用程序逻辑。假设一个视图包含触发事件的用户控件,并且我想向该事件添加一个事件处理程序。该事件处理程序应该在视图的视图模型中,因为它包含业务逻辑。问题是——视图和视图模型仅通过绑定连接;如何使用绑定连接事件处理程序?甚至有可能吗(我怀疑不是)?如果不是 - 我应该如何处理来自视图模型中控件的事件?也许我应该使用命令或 INotifyPropertyChanged?
采纳答案by ThomasAndersson
Generally speaking, it is a good MVVM-practice to avoid code in code behind, as would be the case if you use events in your user controls. So when possible, use INotifyPropertyChanged
and ICommand
.
一般来说,避免代码中的代码是一个很好的 MVVM 实践,就像在用户控件中使用事件一样。因此,如果可能,请使用INotifyPropertyChanged
和ICommand
。
With that said, depending on your project and how pragmatic you are, some times it makes more sense to use the control's code behind.
话虽如此,根据您的项目和您的务实程度,有时使用控件的代码更有意义。
I have at a few occasions used something like this:
我曾在一些场合使用过这样的东西:
private void textBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
MyViewModel vm = this.DataContext as MyViewModel;
vm.MethodToExecute(...);
}
You could also consider Attached Command Behaviour, more info about this and implementations to find here:
您还可以考虑Attached Command Behavior,有关此内容的更多信息以及可在此处找到的实现:
Firing a double click event from a WPF ListView item using MVVM