Combobox binding itemsource to custom list and selecteditem to an instance of that list doesn't work

前端 未结 3 1953
轮回少年
轮回少年 2021-01-13 20:19

I tried really different ways to make my combobox working but I\'m still stuck :(

Here is a very simplified version of my app : (just edited, sorry for mistakes)

3条回答
  •  梦谈多话
    2021-01-13 20:45

    Is the SelectedItem the exact same reference in memory as the item in the ItemsSource?

    By default, WPF will compare the SelectedItem to the items in the ItemsSource by reference, and if they're not the same reference in memory, it will return no matching item.

    If you are unable to do this in your code, the most common workarounds are to either:

    • Bind the SelectedValue to a value type instead of a reference type, and set the SelectedValuePath

      
      
    • Or override the .Equals() to ensure the two objects are considered equal when specific properties match, as opposed to being considered equal when the reference in memory matches.

      public override bool Equals(object obj) 
      { 
          if (obj == null || !(obj is Grade)) 
              return false; 
      
          return ((Grade)obj).GradeId == this.GradeId); 
      }
      

提交回复
热议问题