Reputation: 946
Scenario:
A list of user control of MyControl
type:
public List<MyControl> Controls { get; set; }
public MyControl SelectedControl { get; set; }
A ComboBox
with the ItemsSource
linked to the Controls
property:
<ComboBox ItemsSource="{Binding Path=Controls}" SelectedItem="{Binding Path=SelectedControl}" DisplayMemberPath="HeaderTitle" >
The problem is that the ComboBox
shows the items correctly but when I select an Item it doesn't appear in the ComboBox
. Why?
PS: HeaderTitle
is a DependencyProperty
of the MyControl
type.
Upvotes: 1
Views: 4735
Reputation: 3028
I think this is a duplicate of WPF - Combobox SelectedItem not getting set?
Therefore I'd like to quote Heinz K's answer https://stackoverflow.com/a/3506262/6071619
I had the same problem and solved it by overriding the Equals() Method in my CustomObject and compared the Id Property.
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}"
Upvotes: 3
Reputation: 1998
Try setting the DataContext for the ComboBox?
<ComboBox DataContext="{Binding Controls}" ItemsSource="{Binding Controls}" DisplayMemberPath="HeaderTitle">
You shouldn't have to bind the SelectedItem property as long as the ItemsSource and DisplayMemberPath are set.
Upvotes: 0
Reputation: 436
try to bind it like this..
<ComboBox ItemsSource="{Binding Controls}" SelectedItem="{Binding SelectedControl, Mode=TwoWay}" DisplayMemberPath="{Binding HeaderTitle}" >
you dont really need to have the selected property bound to its class... it can be just a string also. so just store the selected item in type string and then work on getting the items from your list that match that selected item.
Upvotes: 0