WPF - 在视图模型中处理来自用户控件的事件 [英] WPF - Handling events from user control in View Model
问题描述
我正在使用 MVVM 模式构建 WPF 应用程序(这两种技术对我来说都是新技术).我将用户控件用于不包含业务逻辑的可重用功能的简单位,并使用 MVVM 模式来构建应用程序逻辑.假设一个视图包含触发事件的用户控件,并且我想向该事件添加一个事件处理程序.该事件处理程序应该在视图的视图模型中,因为它包含业务逻辑.问题是——视图和视图模型仅通过绑定连接;如何使用绑定连接事件处理程序?甚至有可能吗(我怀疑不是)?如果不是 - 我应该如何处理来自视图模型中的控件的事件?也许我应该使用命令或 INotifyPropertyChanged?
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 中是一个很好的做法,就像在用户控件中使用事件一样.因此,如果可能,请使用 INotifyPropertyChanged
和 ICommand
.
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
.
话虽如此,根据您的项目和您的务实程度,有时使用背后的控件代码更有意义.
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:
触发双击事件从使用 MVVM 的 WPF ListView 项
这篇关于WPF - 在视图模型中处理来自用户控件的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!