问题描述
我将 Horizontal ItemsControl 转换为 Listbox,以便能够选择单个项目,但发现选择已损坏.花了一些时间来提炼出问题所在.
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 problematic bit.
Books = new[] { new Book{Id=1, Name="Book1"},
new Book{Id=2, Name="Book2"},
new Book{Id=3, Name="Book3"},
new Book{Id=4, Name="Book4"},
new Book{Id=3, Name="Book3"},
};
<DataTemplate DataType="{x:Type WPF_Sandbox:Book}">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
<ListBox ItemsSource="{Binding Books}"/>
如果 Book 是一个结构,如果您选择的项目在列表中具有等效结构,则列表框选择(默认模式:单)会出错.例如 Book3
If Book is a struct, the listbox selection (default mode : single) goes awry if you select an item which has an equivalent struct in the list. e.g Book3
如果 Book 变成一个类(具有非值类型语义),则选择是固定的.
If Book is turned into a class (with non-value type semantics), selection is fixed.
选择(到目前为止,不喜欢其中任何一个):
Choices (so far, don't like any of them):
- 我选择了结构体,因为它是一个小型数据结构,并且值类型语义在比较两个实例是否相等时很有用.将其更改为类会导致我失去值类型语义.我不能再使用默认的 Equals 或覆盖它以进行成员比较.
- 添加一个独特的 Book 属性,纯粹是为了让列表框选择起作用(例如,一个索引).
- 消除重复.. 不可能.
WPF 列表框:选择问题:声明列表框正在设置 SelectedItem,并且在为此更新 UI 时,它只是点亮列出列表中 Equal(SelectedItem)
的所有项目.不知道为什么.. 突出 SelectedIndex 会使这个问题消失;也许我错过了一些东西.ListBox 甚至在 SelectionMode="Single" 中也选择了许多项目:当列表项目是字符串(值类型语义)时显示相同的问题
WPF listbox : problem with selection : states that the Listbox is setting SelectedItem and while updating the UI for this, it just lights up all items in the list that Equal(SelectedItem)
. Not sure why.. highlighting SelectedIndex would make this problem go away; maybe I am missing something.ListBox is selecting many items even in SelectionMode="Single" : shows the same problem when list items are strings (value type semantics)
推荐答案
为什么不简单地使用更好的集合类作为数据源来解决问题
Why not simply use a better collection class as your datasource to overcome the problem
var collection = new[]
{
new Book {Id = 1, Name = "Book1"},
new Book {Id = 2, Name = "Book2"},
new Book {Id = 3, Name = "Book3"},
new Book {Id = 4, Name = "Book4"},
new Book {Id = 3, Name = "Book3"},
};
var Books = collection.ToDictionary(b => Guid.NewGuid(), b => b);
DataContext = Books;
这将是您的数据模板
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value.Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
这篇关于列表项是值类型/结构并包含重复项的列表框的选择错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!