WPF MVVM ComboBox SelectedItem or SelectedValue not working

前端 未结 18 2419
一生所求
一生所求 2020-12-05 06:22

Update

After a bit of investigating. What seems to be the issue is that the SelectedValue/SelectedItem is occurring before the Item source is finis

18条回答
  •  星月不相逢
    2020-12-05 07:19

    I had this problem with a ComboBox displaying a list of colors ( List ).
    Selecting a color was possible but it wasnt displayed when the selection closed (although the property was changed!)

    The fix was overwriting the Equals(object obj) method for the type selected in the ComboBox (Brush), which wasnt simple because Brush is sealed. So i wrote a class EqualityBrush containing a Brush and implementing Equals:

    public class EqualityBrush
    {
        public SolidColorBrush Brush { get; set; }
    
        public override bool Equals(object o)
        {
            if (o is EqualityBrush)
            {
                SolidColorBrush b = ((EqualityBrush)o).Brush;
                return b.Color.R == this.Brush.Color.R && b.Color.G == this.Brush.Color.G && b.Color.B == this.Brush.Color.B;
            }
            else
                return false;
        }
    }
    

    Using a List of my new EqualityBrush class instead of normal Brush class fixed the problem!

    My Combobox XAML looks like this:

    
        
            
                
            
        
    
    

    Remember that my "Brush"-Property in the ViewModel now has to be of Type EqualityBrush!

提交回复
热议问题