简体   繁体   English

如何处理MVVM中的事件

[英]How to handle events in MVVM

I am new in MVVM. 我是MVVM的新手。 I just learn this pattern and want to use it in my project. 我只是学习这种模式,并希望在我的项目中使用它。 I am already understand working principle of this pattern and learned how to use Commands. 我已经理解了这种模式的工作原理,并学会了如何使用命令。 But I have question how to handle events of another controls for example ListBox SelectionChanged event. 但我有问题如何处理另一个控件的事件,例如ListBox SelectionChanged事件。 ListBox haven't Command attribute ListBox没有Command属性

You often don't need to. 你经常不需要。 For example, you can just bind the ListBox 's SelectedItem property to a property on your view model: 例如,您可以将ListBoxSelectedItem属性绑定到视图模型上的属性:

<ListBox ItemsSource="{Binding Customers}" SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"/>

Not only does this give you access to the selected customer in your view model, it also allows your view model to dictate the selected customer by setting the property itself. 这不仅可以让您访问视图模型中的选定客户,还可以让您的视图模型通过设置属性本身来指定所选客户。

There are other techniques to "avoid" direct handling of events in your code-behind, too. 还有其他技术可以“避免”直接处理代码隐藏中的事件。 For example, attached behaviors. 例如,附加行为。 However, you shouldn't be scared of handling events directly if the code is solely concerned with the view and makes your code simpler. 但是,如果代码只关注视图并使代码更简单,则不应该害怕直接处理事件。

To add command attribute to your control, it has to inherit from ICommandSource. 要向控件添加命令属性,它必须从ICommandSource继承。 Check this post, to see how it's accomplished. 查看这篇文章,看看它是如何完成的。

The BookLibraray application of the WPF Application Framework (WAF) shows how to listen to WPF events in a Model-View-ViewModel (MVVM) designed application. WPF应用程序框架(WAF)BookLibraray应用程序演示了如何在Model-View-ViewModel(MVVM)设计的应用程序中监听WPF事件。 It allows a user to select multiple books so that he can delete all of them at once. 它允许用户选择多本书,以便他可以一次删除所有书籍。 See class BookLibrary.Presentation.Views.BookView. 请参阅BookLibrary.Presentation.Views.BookView类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM