简体   繁体   中英

How to handle events in MVVM

I am new in 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 haven't Command attribute

You often don't need to. For example, you can just bind the ListBox 's SelectedItem property to a property on your view model:

<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. 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. It allows a user to select multiple books so that he can delete all of them at once. See class BookLibrary.Presentation.Views.BookView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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