简体   繁体   中英

WPF ComboBox doesn't show selection

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.

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}"

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.

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.

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