Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

wpf - 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.

question from:https://stackoverflow.com/questions/1384369/mvvm-binding-to-listbox-selecteditem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...