WPF Listbox binding: SelectedItem not setting

12,636

You need to bind to the SelectedProperty:

<ListBox ItemsSource="{Binding Properties}" 
 DisplayMemberPath="Name" 
 SelectedItem="{Binding SelectedProperty}"  />
Share:
12,636
GarethD
Author by

GarethD

Senior Analyst working with SQL-Server

Updated on June 08, 2022

Comments

  • GarethD
    GarethD almost 2 years

    I have a ListBox simplified to the following XAML

    <ListBox ItemsSource="{Binding Properties}" 
         DisplayMemberPath="Name" 
         SelectedItem="SelectedProperty" />
    

    and in my ViewModel:

    private List<Property> propertyList;
    private Property selectedProperty;
    public List<Property> Properties 
    { 
        get 
        { 
            return propertyList; 
        } 
        set 
        { 
            propertyList = value;
            NotifyPropertyChanged("Properties");
        } 
    }
    public Property SelectedProperty
    {
        get
        {
            return selectedProperty;
        }
        set
        {
            NotifyPropertyChanged("SelectedProperty");
            selectedProperty= value;
        }
    }
    

    My List box populates fine, but no matter what I try I cannot seem to get the SelectedProperty to update when I select an item in my list box. I have tried switching it all around to use ObservableCollection rather than List and adding an Event handler for CollectionChanged, but this has not worked.

    I am sure I am missing something stupid, and cannot see the wood for the trees. I am reaching the end of my tether and need someone to step in and help.