Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle events in MVVM

Tags:

c#

events

mvvm

wpf

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

like image 931
Polaris Avatar asked Aug 24 '10 06:08

Polaris


People also ask

Is MVVM deprecated?

This is the same MVVM library used by the Microsoft Store, the Photos app, and more! The MVVM Toolkit is inspired by MvvmLight, and is also the official replacement for it now that the library has been deprecated.

When should MVVM be used?

MVVM is enough for small projects, but when your codebase becomes huge, your ViewModel s start bloating. Separating responsibilities becomes hard. MVVM with Clean Architecture is pretty good in such cases. It goes one step further in separating the responsibilities of your code base.

What are routed events in WPF?

A routed event is an event registered with the WPF event system, backed by an instance of the RoutedEvent class, and processed by the WPF event system. The RoutedEvent instance, obtained from registration, is typically stored as a public static readonly member of the class that registered it.

What is MVVM command?

Commands are an implementation of the ICommand interface that is part of the . NET Framework. This interface is used a lot in MVVM applications, but it is useful not only in XAML-based apps.


1 Answers

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.

like image 154
Kent Boogaart Avatar answered Sep 23 '22 08:09

Kent Boogaart