Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM: Binding to ListBox.SelectedItem?

How do I bind a view model property to the ListBox.SelectedItem property?

I have created a simple MVVM demo to try to figure this one out. My view model has these properties:

private ObservableCollection<DisneyCharacter> p_DisneyCharacters; public ObservableCollection<DisneyCharacter> DisneyCharacters {     get { return p_DisneyCharacters; }      set     {         p_DisneyCharacters = value;         base.FirePropertyChangedEvent("DisneyCharacters");     } }  private DisneyCharacter p_SelectedItem; public DisneyCharacter SelectedItem {     get { return p_SelectedItem; }      set     {         p_SelectedItem = value;         base.FirePropertyChangedEvent("SelectedItem");     } } 

I want to bind the SelectedItem property to the item selected in the list box. Here is the XAML for the list box:

<ListBox ItemTemplate="{StaticResource MasterTemplate}"          ItemsSource="{Binding Path=DisneyCharacters}"           SelectedItem="{Binding Path=Selectedtem, Mode=TwoWay}"           HorizontalAlignment="Stretch" /> 

Here is my problem: The view model SelectedItem property isn't being updated when I change the selection in the list box.

I did a test where I temporarily replaced the view model SelectedItem property with a SelectedIndex property, and I bound that to the ListBox.SelectedIndex property. That property updated fine--it's just the SelectedItem property that I can't get to work.

So, how do I fix the SelectedItem binding? Thanks for your help.

like image 480
David Veeneman Avatar asked Sep 05 '09 22:09

David Veeneman


1 Answers

Well, there it is, big as life. In the XAML. I am binding to a view model property "Selectedtem". Unfortunately, the actual name is "SelectedItem". So this code actually works--I solved the problem early this afternoon and then spent the rest of the afternoon and all evening scouring the web, before I noticed the spelling error.

My wife told me at 3:00 this afternoon, "You know, it's going to turn out to be something small." And so it did--a missing letter "I". Well, at least I can go to bed now.

like image 149
David Veeneman Avatar answered Sep 20 '22 21:09

David Veeneman