更改列表框的比较器
我有一个列表框,其中包含工作项列表(来自 TFS)。我想添加要选择的项目,但无法将这些项目识别为相同的项目。
这是我的代码,
public void SelectQueryResultItem(WorkItem item)
{
lstQueryResults.SelectedItems.Add(item);
}
当传入的 WorkItem 来自 SelectedItems 列表中的同一查询时,这非常有效。但是,如果它来自不同的查询(即对象引用不同),则它无法正确识别对象。
我认为它是在参考上进行比较。我想覆盖它并使其与 item.Id 进行比较。有办法做到这一点吗?
请注意,我正在使用 WPF ListBox ,而不是 WinForms ListBox
I have a list box that contains a list of WorkItems (from TFS). I want to add items to be selected, but it is failing to identify the items as the same.
Here is my code
public void SelectQueryResultItem(WorkItem item)
{
lstQueryResults.SelectedItems.Add(item);
}
This works great when the WorkItem passed in is from the same query that is in the SelectedItems list. However if it came from a different query (ie the object reference is not the same) then it does not identify the object correctly.
I assume it is comparing on reference. I want to override that and make it compare on item.Id. Is there a way to do that?
Note that I am using the WPF ListBox, not the WinForms ListBox
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过重写 WorkItem 类上的 Equals 以按 ID 进行比较,而不是从 ListBox 继承?这并不理想,因为显然具有相同 ID 的两个实例不一定相等。但我不确定如何诱使 Selector 基类使用自定义 IComparer。
编辑
我深入研究后发现,您可以从 CollectionView(它是要在 WPF 中绑定的集合的包装器)派生并重写其 Comparer 属性以返回自定义 IComparer。因此,您可以创建类似 WorkItemCollectionView 的内容来覆盖 Comparer 并返回类似 WorkItemIDComparer 的内容。
希望这有帮助。
Rather than inherit from ListBox, have you tried overriding Equals on the WorkItem class to do a comparison by ID? It's not ideal since obviously two instances with the same ID are not necessarily equal. But I'm not sure how you might coax the Selector base class into using a custom IComparer.
EDIT
I dug in a little deeper and found that you can derive from CollectionView (which is a wrapper around a collection to be bound in WPF) and override its Comparer property to return a custom IComparer. So you could create something like a WorkItemCollectionView that overrides Comparer and return something like a WorkItemIDComparer.
Hope this helps.
这是解决此问题的一种不太酷的方法。
基本上我绕过了列表框中的比较系统。
如果 WPF 允许我访问比较器,那就太好了,这样我就可以按值进行比较(如果我愿意),而不需要这样做。
Here is a non-cool way to solve this issue.
Basically I am circumventing the compare system in the ListBox.
It would be nice if WPF allowed me to have access to the comparer so I can compare by value if I want to and not need to do this.