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

前端 未结 3 1157
不思量自难忘°
不思量自难忘° 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:40

    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

    0 讨论(0)
  • 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();
        }
    }
    
    0 讨论(0)
  • 2021-01-02 08:59

    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?

    0 讨论(0)
提交回复
热议问题