Let's first look at the demo program. Before you fix the issue, selecting duplicate numbers will lead to confusion in the selected status, and multiple numbers may be inexplicably selected.
Root problem. The problem is finally located in the following code (WPF project, Silverlight project is similar ):
/*internal bool Select(object o, bool assumeInItemsCollection); Declaring Type: System.Windows.Controls.Primitives.Selector+SelectionChanger Assembly: PresentationFramework, Version=4.0.0.0 */internal bool Select(object o, bool assumeInItemsCollection){ if (!Selector.ItemGetIsSelectable(o)) return false; if (!assumeInItemsCollection && !this._owner.Items.Contains(o)) { if (!this._toDeferSelect.Contains(o)) this._toDeferSelect.Add(o); return false; } if (!this._toUnselect.Remove(o)) { if (this._owner._selectedItems.Contains(o)) return false; if (this._toSelect.Contains(o)) return false; if (!this._owner.CanSelectMultiple && this._toSelect.Count > 0) { foreach (object obj2 in (IEnumerable) this._toSelect) { this._owner.ItemSetIsSelected(obj2, false); } this._toSelect.Clear(); } this._toSelect.Add(o); } return true;}
Because items. Contains (o) is used for determination, duplicate data of the value type may be judged incorrectly. The idea to solve this problem is to convert the value type to the reference type.
Create the following code:
public class WrapObject<T> { private T _obj; public WrapObject(T o) { _obj = o; } public static implicit operator WrapObject<T>(T o) { return new WrapObject<T>(o); } public static explicit operator T(WrapObject<T> o) { return o._obj; } public T UnWrap() { return _obj; } public override string ToString() { return _obj == null ? null : _obj.ToString(); } }
Bind method
listBox2.ItemsSource = new WrapObject<int>[] { 1, 2, 3, 4, 5, 6, 1, 4, 5, 2, 3, 6 };
Solve this problem