wpfbindingcomboboxselecteditemitemssource

WPF - Combobox SelectedItem not getting set?


I have a ComboBox that has its ItemsSource bound to a static List<CustomSettings> of options. The ComboBox is part of a form which is bound to a CustomObject class, and one of the properties on that class is a CustomSettingProperty.

I would like to bind the SelectedItem of the ComboBox to the property specified in the CustomObject, however SelectedItem="{Binding Path=CustomSettingProperty}" is not setting the default selected item. Using breakpoints I can see that it is calling the get; method, so I think the problem might be in the fact the CustomSettingProperty is created separately from the List<CustomObject> so WPF does not think it is the same item.

Is there an easy way to do this? Or perhaps an alternative since the CustomSettings class does contain an Id?


Solution

  • If the item that is selected is not the same instance that is contained in the List, you must override Equals() in the CustomObject to let the ComboBox know that it is the same object.

    If it's the same instance, maybe it's only a simple thing such as setting the BindingMode to TwoWay:

    SelectedItem="{Binding Path=CustomSettingProperty,Mode=TwoWay}"