Selection bug for listbox where the list items are value types / structs and contain duplicates?

前端 未结 4 1960
耶瑟儿~
耶瑟儿~ 2020-12-19 16:04

I turned an Horizontal ItemsControl to a Listbox so that I am able to select individual items but found that the selection was broken. Took some time to distill out the prob

4条回答
  •  鱼传尺愫
    2020-12-19 16:54

    Thanks to Dean Chalk for his idea.

    I extend it so that it is easier to user for other structs

    The idea is to use a converter to cast the original struct collection to a custom collection, which in turn override the equal to compare with Guid ID. You still has the original order

    public class StructListItem
    {
        private Guid _id = Guid.NewGuid();
        public Guid ID
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
            }
        }
    
        private object _core = default(object);
        public object Core
        {
            get
            {
                return _core;
            }
            set
            {
                _core = value;
            }
        }
    
        public StructListItem(object core)
        {
            Core = core;
        }
    
        public override bool Equals(object obj)
        {
            return ID.Equals(obj);
        }
    
        public override int GetHashCode()
        {
            return ID.GetHashCode();
        }
    }
    
    public class StructToCollConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is IEnumerable)
            {
                List _ret = new List();
                if (value != null)
                {
                    IEnumerator i = ((IEnumerable)value).GetEnumerator();
                    while (i.MoveNext())
                    {
                        _ret.Add(new StructListItem(i.Current));
                    }
                }
                return _ret.ToArray();
            }
    
            return null;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

        
            
                
                    
                        
                    
                
            
    
        
    

提交回复
热议问题