我这样定义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);
有人知道吗?
答案 0 :(得分:3)
你应该问自己的第一件事是......
为什么我要将排序描述添加到CollectionViewSource 并过滤到视图?我不应该把它们都添加到 同一个对象?
答案是肯定的!
要直接向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;
}
显然,它会覆盖您在View上设置的过滤器。
如果你仍然好奇,这里是source code for CollectionViewSource。