13

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?

Rachel
  • 130,264
  • 66
  • 304
  • 490
  • Can you give the code for CustomSettingProperty? And possibly an example of how you are setting it? – jsmith Aug 17 '10 at 19:35

2 Answers2

27

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}"
Heinz K
  • 410
  • 5
  • 6
  • 2
    Thank you! I can't believe I didn't think about overriding Equals... I won't be making that mistake again (I hope) – Rachel Aug 17 '10 at 19:45
  • I have the same problem but I have been overridden `Equals()` How can I setting the BindingMode? Note: I am using c# and Winforms – Cristhian Boujon Mar 14 '13 at 03:17
  • Mode is TwoWay by default is it not? – Brock Hensley Aug 16 '13 at 12:27
  • From MSDN > A programmatic way to determine whether a dependency property binds one-way or two-way by default is to get the property metadata of the property using GetMetadata and then check the Boolean value of the BindsTwoWayByDefault property. – Maxence Feb 27 '14 at 11:34
  • Thanks @Heinz K but how to override Equals()? Can you please give small example. – LightTechnician Jun 26 '15 at 07:48
  • 1
    In my case just simply override Object.Equals throws StackOverflowException. I think the whole answer is to implement full IEquatable that means implementing its Equals method and overriding Object.Equals(Object) and Object.GetHashCode methods as in [this example](https://msdn.microsoft.com/en-us/library/ms131190(v=vs.110).aspx) (see the end of "Remarks" section - "Notes to Implementers" - and "Examples" section). – Alex34758 Jul 26 '16 at 13:06
0

I found the solution, It was The Prism's Event Aggregator was passed with reference type so That the ui thread stops processing

Mohamed Elhakim
  • 204
  • 1
  • 3
  • 7