views:

2052

answers:

3

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.

+2  A: 

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.

David Veeneman
To help you find these problems sooner, if you debug your app you should see a WPF binding error in the Output window of Visual Studio, indicating that the property "Selectedtem" doesn't exist. Hopefully that would help you to track down this sort of error quicker in the future.
Andy
A: 

Thanks David you saved me a lot of time

Rob
A: 

Good one... Saved lot of time... You did this 09 I am using in 10! :)

gss