I have a ComboBox that has an ItemsSource associated with an ObservableCollection<CustomObject> , where CustomObject has several properties.
Class Example:
public class CustomObject : INotifyPropertyChanged { public string Property1 { } public string Property2 { } public string Property3 { } }
The SelectedItem property of my ComboBox tied to the CustomObject property that appears in the DataGrid row.
Class Example:
public class DataGridEntry : INotifyPropertyChanged { public CustomObject Column1 { } public string Column2 { } public string Column3 { } }
I create an ObservableCollection<CustomObject> during the initialization of my window, and then set the data context of my DataGrid to an ObservableCollection<DataGridEntry> .
My task is to load the initial values ββinto my DataGrid , but I do not know how to make the ComboBox clear that the specified CustomObject can be found in its ItemsSource , and therefore, ComboBox > does not display a SelectedItem .
This is how I load the initial values:
ObservableCollection<DataGridEntry> entries = new ObservableCollection<DataGridEntry>(); MyWindow.DataContext = this; entries.Add(new DataGridEntry(new CustomObject("val1", "val2", "val3"), "col2", "col3");
Did you know that I set the ComboBox its SelectedItem property as follows? If I change my code so that the DataGridEntry only works with string properties, then the ComboBox displays the SelectedItem after initialization, as I expect. For reference types, it does not work.
If necessary, I bind the data to the
ComboBox :
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.CustomObjectsCollection}" SelectedItem="{Binding Column1, UpdateSourceTrigger=PropertyChanged}"/>
EDIT:
In case it is not clear, the ObservableCollection<CustomObject> element contains an element that is set in the same way as above: new CustomObject("val1", "val2", "val3");
I suspect that the ComboBox does not understand that the two CustomObjects equivalent. And because of this suspicion, I overridden the Equals and GetHashCode functions for CustomObject , without any success. There seems to be no problem in ComboBox finding equality for nonreferenced data types such as strings. Thanks for the help!:)