列表框的选择错误,其中列表项是值类型/结构并包含重复项? [英] Selection bug for listbox where the list items are value types / structs and contain duplicates?

查看:76
本文介绍了列表框的选择错误,其中列表项是值类型/结构并包含重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Horizo​​ntal ItemsControl转到了一个列表框,这样我可以选择单个项目,但是发现选择被破坏了.花了一些时间来蒸馏出有问题的部分.

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,并且在为此更新用户界面时,它只是亮起列出Equal(SelectedItem)列表中的所有项目.不知道为什么.突出显示SelectedIndex会使这个问题消失.也许我想念一些东西. 即使在SelectionMode ="Single" 中,ListBox也会选择许多项:当列表项是字符串(值类型语义)时,也会出现相同的问题

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;

这将是您的DataTemplate

And this will be your DataTemplate

<ListBox ItemsSource="{Binding}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Value.Name}"/>
    </DataTemplate>
  </ListBox.ItemTemplate>

这篇关于列表框的选择错误,其中列表项是值类型/结构并包含重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆