问题描述
我遇到了一些很奇怪的简单 WPF 应用程序
I have encountered something very strange, simple WPF application
<Window x:Class="ListBoxSelection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox ItemsSource="{Binding Path=Strings}" SelectionMode="Single"/>
</Grid>
</Window>
后面有代码
public class ViewModel
{
public List<string> Strings { get; set; }
public ViewModel ()
{
Strings = new List<string> ();
Strings.Add ("A");
// add many items ...
Strings.Add ("A");
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow ()
{
InitializeComponent ();
DataContext = new ViewModel ();
}
}
当我点击单个项目时,
如果我继续点击项目,它们只会聚合.单击已选择的项目没有任何作用.挠我的脑袋,我以前有到 ListBoxes 的数据绑定列表,而且以前从未见过这个.运行 Win7 (64)、VS2010,行为显示为 .Net 3.5、.Net 3.5 Client Profile、.Net 4 和 .Net 4 Client Profile.
if I continue clicking items, they just aggregate. Clicking an already selected item does nothing. Scratching my head, I have databound lists to ListBoxes before, and have never seen this before. Running Win7 (64), VS2010, behaviour presents with .Net 3.5, .Net 3.5 Client Profile, .Net 4, and .Net 4 Client Profile.
Arg,我应该提到我期待正常的、默认的、单选行为.
Arg, I should mention I am expecting normal, default, single-select behaviour.
推荐答案
Dan Bryant 在他的评论中得到了大部分答案.
Dan Bryant got most of the answer in his comment.
这里发生的是字符串实习.当您创建一组具有相同值的字符串时,.Net 通过让对同一字符串值的所有引用实际引用同一字符串对象来节省内存使用量.(例如,请参阅this,了解详情.)
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.)
我真的不知道为什么 ListBox 的行为与它完全一样,即第一次选择列表中的任何项目时,它会同时选择该项目和列表中的第一项.但是当您点击一个新项目时它不会取消选择,因为检查 SelectedItem
是否与您刚刚点击的项目不同,但事实并非如此.
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.
通过将 ListBox 绑定到一组测试对象,我得到了完全相同的行为:
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();
}
}
在MainWindow.xaml
中:
<ListBox x:Name="MyListBox" ItemsSource={Binding}"/>
在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;
这篇关于即使在 SelectionMode="Single" 中,ListBox 也选择了许多项目.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!