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

前端 未结 2 466
悲&欢浪女
悲&欢浪女 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:

    <ListBox x:Name="MyListBox" ItemsSource={Binding}"/>
    

    In MainWindow.xaml.cs:

    ObservableCollection<TestObject> test = new ObservableCollection<TestObject>();
    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;
    
    0 讨论(0)
  • 2021-01-02 18:01

    I encountered this problem as well--as others have noted, .NET handles strings in a curious manner to improve memory management.

    My immediate workaround was to create a UniqueListItem class to be used in place of the strings I was planning to add to the listbox.

    class UniqueListItemObject
    {
        private string _text;
        public string Text { get { return _text; } set { _text = value; } }
    
        public UniqueListItemObject(string input)
        {
            Text = input;
        }
        public UniqueListItemObject()
        {
            Text = string.Empty;
        }
    
        public override string ToString()
        {
            return Text;
        }
    }
    

    Because each instance of this object will get its own memory location, adding instances of this object to a listbox control instead of adding strings will result in unique selections, even if the strings displayed in the listbox are identical.

            yourListBox.Items.Add(new UniqueListItemObject(yourStringHere);
    

    I can't say if this is the best solution (that depends on your project's requirements) but hopefully someone finds this helpful.

    0 讨论(0)
提交回复
热议问题