How do you bind a ComboBox's SelectedItem to an object that is a copy of an item from ItemsSource?

前端 未结 3 1221
不思量自难忘°
不思量自难忘° 2021-01-02 08:14

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         


        
3条回答
  •  旧巷少年郎
    2021-01-02 08:52

    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();
        }
    }
    

提交回复
热议问题