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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With