Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Listbox binding: SelectedItem not setting

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.

like image 572
GarethD Avatar asked May 15 '26 01:05

GarethD


1 Answers

You need to bind to the SelectedProperty:

<ListBox ItemsSource="{Binding Properties}" 
 DisplayMemberPath="Name" 
 SelectedItem="{Binding SelectedProperty}"  />
like image 60
devdigital Avatar answered May 16 '26 14:05

devdigital