I am using the MVVM template with WPF and have encountered a problem that I can simplify to the following:
I have a CardType model.
public class CardType { public int Id { get; set; } public string Name { get; set; } }
And I have a viewmodel that uses CardType.
public class ViewModel : INotifyPropertyChanged { private CardType selectedCardType; public CardType SelectedCardType { get { return selectedCardType; } set { selectedCardType = value; OnPropertyChanged(nameof(SelectedCardType)); } } public IEnumerable<CardType> CardTypes { get; set; }
My XAML has a ComboBox that bases its elements on CardTypes and must first select an element based on SelectedCardType.
<ComboBox ItemsSource="{Binding CardTypes}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedCardType}"/>
For reasons beyond my control, the SelectedCardType object will be an unequal copy reference of an element in CardTypes. So WPF cannot match SelectedItem with an item in ItemsSource, and when I launch the application, ComboBox initially appears without a selected item.
I tried to override the Equals () and GetHashCode () methods in CardType, but WPF still does not match the elements.
Given my particular limitations, how can I get ComboBox to select the correct item?
source share