I\'m using the MVVM pattern with WPF and have run into a problem, which I can simplify to the following:
I have a CardType model.
public class CardTy
You can use SelectedValue and SelectedValuePath:
<ComboBox ItemsSource="{Binding CardTypes}"
DisplayMemberPath="Name"
SelectedValue="{Binding ProductId, Mode=TwoWay}"
SelectedValuePath="Id"/>
Where ProductId is a int property with NotifyPropertyChanged.
Read a great explanation here: Difference between SelectedItem, SelectedValue and SelectedValuePath
You might not be overriding Equals
and GetHashCode
properly. This should work for you. (However, just overriding Equals will work in your case but it's considered to be good practice to override GetHashCode too when you override Equals for a class)
public class CardType
{
public int Id { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
CardType cardType = obj as CardType;
return cardType.Id == Id && cardType.Name == Name;
}
public override int GetHashCode()
{
return Id.GetHashCode() & Name.GetHashCode();
}
}
A workaround that you could do is to bind your SelectedItem to a string (instead of cardType), then create an object of type CardType using this string?