在之前引入sortdescription时,CollectionViewSource Filter不工作
本文关键字:CollectionViewSource Filter 工作 sortdescription | 更新日期: 2023-09-27 18:06:14
我这样定义了一个CollectionViewSource
,但似乎过滤器不起作用。
CollectionViewSource cvs = new CollectionViewSource();
//oc IS AN OBSERVABLE COLLECTION WITH SOME ITEMS OF TYPE MyClass
cvs.Source = oc;
//IsSelected IS A bool? PROPERTY OF THE MyClass
cvs.View.Filter = new Predicate<object>(input=>(input as MyClass).IsSelected == true);
//Major IS AN string PROPERTY OF THE MyClass
cvs.SortDescriptions.Add(new SortDescription(
"Major", ListSortDirection.Ascending));
然而,我这样改变了代码,一切都解决了!
CollectionViewSource cvs = new CollectionViewSource();
cvs.Source = oc;
cvs.SortDescriptions.Add(new SortDescription(
"Major", ListSortDirection.Ascending));
cvs.View.Filter = new Predicate<object>(input=>(input as MyClass).IsSelected == true);
有谁知道方法吗?
你首先应该问自己的是……
为什么我要添加排序描述到CollectionViewSource和过滤器到视图?我不是应该把它们都加到相同的对象?
答案是YES!
要直接向CollectionViewSource
添加过滤器逻辑,您需要为Filter
事件添加一个事件处理程序。
直接从MSDN,这里是一个例子
listingDataView.Filter += new FilterEventHandler(ShowOnlyBargainsFilter);
private void ShowOnlyBargainsFilter(object sender, FilterEventArgs e)
{
AuctionItem product = e.Item as AuctionItem;
if (product != null)
{
// Filter out products with price 25 or above
if (product.CurrentPrice < 25)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
}
现在,至于为什么当您添加排序描述时将删除过滤器。
当您将SortDescription
添加到CollectionViewSource
时,在幕后它最终会到达这个代码块。
Predicate<object> filter;
if (FilterHandlersField.GetValue(this) != null)
{
filter = FilterWrapper;
}
else
{
filter = null;
}
if (view.CanFilter)
{
view.Filter = filter;
}
显然,它覆盖了您在视图上设置的过滤器。
如果您仍然好奇,这里是CollectionViewSource的源代码。