ListBox is selecting many items even in SelectionMode=“Single”

前端 未结 2 489
悲&欢浪女
悲&欢浪女 2021-01-02 16:59

I have encountered something very strange, simple WPF application



        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 17:50

    Dan Bryant got most of the answer in his comment.

    What's going on here is string interning. When you create a bunch of strings with the same value, .Net saves on memory usage by having all references to the same string value actually refer to the same string object. (See this, for instance, for details.)

    I don't really know why the ListBox behaves exactly the way it does, which is that the first time you select any item in the list, it selects both that item and the first item in the list. But it doesn't unselect when you click on a new item because checks to see if the SelectedItem is different from the item you just clicked on, and it isn't.

    I got exactly the same behavior by binding a ListBox to a collection of test objects:

    public class TestObject
    {
        public override string ToString()
        {
            return GetHashCode().ToString();
        }
    }
    

    In MainWindow.xaml:

    
    

    In MainWindow.xaml.cs:

    ObservableCollection test = new ObservableCollection();
    TestObject t = new TestObject();
    test.Add(t);
    test.Add(t);
    test.Add(t);
    test.Add(t);
    test.Add(t);
    test.Add(t);
    MyListBox.DataContext = test;
    

提交回复
热议问题