问题描述
我的Vehicle
模型中有两个属性:Category
和Name
。
我有一个名为VehiclesView
的ICollectionView。
绑定到Category
时,ListView显示:
Airplane
Helicopter
Helicopter
Airplane
Car
Car
我必须能够过滤VehiclesView
,以删除同一Category
的重复项,从而导致:
Airplane
Car
Helicopter
要求:过滤逻辑必须使用FilterEventArgs,如下所示:
public void ApplyFilter(object sender,FilterEventArgs e)
{
Vehicle v = e.Item as Vehicle;
if (v != null)
{
// Remove duplicate instances of Category
if (??????????????)
{
e.Accepted = false;
}
else
{
e.Accepted = true;
}
}
}
我只需要有关过滤逻辑的帮助。
非常感谢您的帮助。
编辑1:“类别”是用户定义的,这意味着过滤器必须在运行时比较属性值并删除重复项。
编辑2:添加了所进行的所有研究的链接,这些链接都没有提供我需要的过滤器逻辑,但是确实提供了其他类型的过滤器逻辑以及如何实现过滤/排序/分组的“大图”。
https://weblogs.asp.net/monikadyrda/wpf-listcollectionview-for-sorting-filtering-and-grouping
http://wpftutorial.net/DataViews.html
C# - how to get distinct items from a Collection View
https://social.technet.microsoft.com/wiki/contents/articles/26673.wpf-collectionview-tips.aspx
http://www.abhisheksur.com/2010/08/woring-with-icollectionviewsource-in.html
Implementing a ListView Filter with Josh Smith's WPF MVVM Demo App
解决方法
您可以创建查找表:
private HashSet<object> ExistingItemsTable { get; } = new HashSet<object>();
private void ApplyFilter(object sender,FilterEventArgs e)
{
if (this.ExistingItemsTable.Contains(e.Item))
{
// FilterEventArgs.Accepted is true by default
e.Accepted = false;
return;
}
this.ExistingItemsTable.Add(e.Item);
}
您需要订阅源集合的CollectionChanged
事件以维护查找表:删除项目时,还需要从表中删除它们。