Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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.

See Question&Answers more detail:os

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

1 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...