views:

80

answers:

1

I'm using MVVM Light on an Windows Phone app. I would like to set the selected item on a listbox after it is databound.

I thought the best way to do this is to setup an eventToCommand on the listbox for the Loaded event and pass the element to set the selected index, but I'm not sure how I can pass the listbox element to the RelayCommand.

+5  A: 

Think about this from the perspective of your viewmodel not in terms of the controls in your view...

Bind the SelectedItem property of the listbox to a new MySelectedItem property on your viewmodel and then you can do it all in the viewmodel without any commands.

For instance you might iterate through the collection of items in your viewmodel that are bound to the ItemsSource of you listbox and then assign one of them to your new MySelectedItem property, and automagically it will show up as selected in the UI.

As an an alternative you can also bind the IsSelected property of EVERY ListBoxItem to a new MyIsSelected property on each object in the collection. Same end result... use whichever approach suits you situation and/or taste...

Scrappydog
I have successfully used the first solution, but you have to make sure you set the binding mode to TwoWay or the binding back to the ViewModel won't take.
Chris Koenig