views:

87

answers:

1

I started using MVVM-Light with WPF yesterday and it really makes a difference when it comes to structuring the code. But now i'm trying to figure out how to handle event.

Lets say I've got this view, with a TabControl. In every TabItem i have a ListBox. Now how do i handle the event SelectionChanged? And to mess things up, can i send the ListBox with the event as a parameter?

I'm very thankful for a simple code-sample.

+2  A: 

In the case of selection changed events, it's better to use WPF built-in support for that: create an ICollectionView that wraps your collection, bind it to an ItemsControl (ListBox etc.) and the ICollectionView will have its CurrentItem automatically synchronized to the current selection. Of course, this only works for single selection.

For more complex events that you can't handle cleanly in a MVVM manner, it's always better to use the Messenger class in MVVM Light to send messages and have them caught by a listener; for example, the View can send a NotificationMessage and the ViewModel can register as a recipient with Messenger.Register (I think it's called). It's a very extensible mechanism - you can also send an action (Action<> or Func<> or whatever) to be executed by the other side etc. etc.

These tips got me through two medium-sized LOB applications without a hitch.

Alex Paven