1

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.

rPulvi
  • 946
  • 8
  • 33
  • Are you trying to set it from code? Because in that case you need to implement INotifyPropertyChanged and raise the PropertyChanged event when setting the SelectedControl property – sondergard Sep 11 '14 at 21:02
  • I'm using the MVVM pattern. The INotifyPropertyChanged is well implemented. – rPulvi Sep 12 '14 at 06:51

3 Answers3

3

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}"
Community
  • 1
  • 1
phifi
  • 2,783
  • 1
  • 21
  • 39
0

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.

Jay Nirgudkar
  • 426
  • 4
  • 18
0

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.

Jaime Still
  • 1,949
  • 20
  • 31
  • If you set the DataContext to Controls you can't set the ItemsSource to Controls... – rPulvi Sep 11 '14 at 13:20
  • You can set the DataContext for the container that the ComboBox is a child of? Could you post the definition of the HeaderTitle property as well as how you are populating MyControl objects to the list? – Jaime Still Sep 11 '14 at 13:22
  • SelectedItem property is different. It is never used to show the item in the combobox. – Jay Nirgudkar Sep 11 '14 at 13:27