简体   繁体   中英

WPF Listbox binding - SelectedItem remains null

I am playing around with MVVM and binding. More specifically a ListBox that shows a collection of objects:

<ListBox ItemsSource="{Binding Scouts}" SelectedItem="{Binding SelectedScout, Mode=TwoWay}/>

In my ViewModel it looks like this:

private ObservableCollection<Scout> scouts;
    private Scout selectedScout;

    public Scout SelectedScout
    {
        get { return selectedScout; }
        set
        {
            OnPropertyChanged("SelectedScout");
            value = selectedScout;
        }
    }

    public ObservableCollection<Scout> Scouts
    {
        get { return scouts; }
        set
        {
            OnPropertyChanged("Scouts");
            scouts = value; 
        }
    }

Now, the ListBox shows the Items in the Collection just fine, but what I want to do is click an item in the Box, and then show further details on that item in a TextBox. I figured I would bind the ListBox' SelectedItem property to a Selected-property in my ViewModel (as shown above) and bind the property to the TextBox like so:

<TextBox Text="{Binding SelectedScout.Id}"/>

But it doesn't work. The TextBox remains blank when I select an item in the ListBox, and I figure it's because my SelectedScout property remians null.

I have been struggling with this problem for a while now, and I just can't seem to find the soloution. I don't know what I am missing.

Thank you in advance for your help.

**EDIT: I solved the problem. Thank you for your answers, but the mistake was in this line:

 public Scout SelectedScout
    {
        get { return selectedScout; }
        set
        {
            OnPropertyChanged("SelectedScout");
            *value = selectedScout;*
        }
    }

Where it should, of course, be:

selectedScout = value;

I feel really stupid now. Thank you for your help.

**

Binding list of objects with XAML

This is proper example for insert update delete selected index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM