tags:

views:

108

answers:

3

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

+9  A: 

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.

HTH,
Kent

Kent Boogaart
Interesting idea. For example I want to handle Mouse RightClick event on DataGrid. In this case do I have to write handler in code behind or must to use attached bahavior?
Polaris
@ Polaris. look at the mvvm frameworks (cinch, mvvm light ...) out there. you will find implementations like EventToCommand Behavior where you can bind events to commands. and like kent said: feel free to you use codebehing when coding view related stuff :) for example BringToView the selected item in a grid or listbox
blindmeis
+1 for the comment about handling events when they only affect the view layer. So many people forget this...
Cameron MacFarland
A: 

To add command attribute to your control, it has to inherit from ICommandSource. Check this post, to see how it's accomplished.

Vitalij
A: 

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.

jbe