WPF - 在View Model中处理来自用户控件的事件 [英] WPF - Handling events from user control in View Model
问题描述
一般来说,这是一个很好的MVVM实践,以避免代码背后的代码,如果您在用户控件中使用事件就会如此。所以,如果可能,请使用 INotifyPropertyChanged
和 ICommand
。
据说,根据你的项目和你的实际情况,有时候使用控件的代码更有意义。
我有几次使用这样的东西:
private void textBox1_MouseDoubleClick(object sender,MouseButtonEventArgs e)
{
MyViewModel vm = this.DataContext as MyViewModel;
vm.MethodToExecute(...);
}
您还可以考虑附加的命令行为,关于这个的更多信息和在这里找到的实现: p>
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?
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:
Firing a double click event from a WPF ListView item using MVVM
这篇关于WPF - 在View Model中处理来自用户控件的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!