I have a ComboBox which has its ItemsSource bound to an ObservableCollection<CustomObject> where CustomObject has a few properties.
Sample class:
public class CustomObject : INotifyPropertyChanged
{
public string Property1 { /*...omitted for brevity...*/ }
public string Property2 { /*...omitted for brevity...*/ }
public string Property3 { /*...omitted for brevity...*/ }
}
The SelectedItem property of my ComboBox is bound to a CustomObject property which appears in a DataGrid row.
Sample class:
public class DataGridEntry : INotifyPropertyChanged
{
public CustomObject Column1 { /*...omitted for brevity...*/ }
public string Column2 { /*...omitted for brevity...*/ }
public string Column3 { /*...omitted for brevity...*/ }
}
I create the ObservableCollection<CustomObject> during the initialization of my window and then set the data context of my DataGrid to an ObservableCollection<DataGridEntry>.
My objective is to load initial values into my DataGrid, but I do not know how to make the ComboBox realize that the CustomObject specified can be found in its ItemsSource, and consequently, the ComboBox does not render a SelectedItem.
Here 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");
Do you know how I make the ComboBox set its SelectedItem property like this? If I change my code so that DataGridEntry works only with string properties, then the ComboBox renders the SelectedItem after initializing as I expect. For reference types, it is not working though.
In case it is needed, this is how 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> contains an element which is instatiated the same as above: new CustomObject("val1", "val2", "val3");
I suspect that the ComboBox doesn't realize that the two CustomObjects are equivalent. And because of this suspicion, I overrode the Equals and GetHashCode functions for CustomObject, with no success. Apparently, the ComboBox has no problem detecting equality for non-reference data types such as strings.
Thanks for the help! :)