C# 以前引入SortDescriptions时CollectionViewSource筛选器不工作

C# 以前引入SortDescriptions时CollectionViewSource筛选器不工作,c#,wpf,collectionviewsource,C#,Wpf,Collectionviewsource,我这样定义了一个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.Fi

我这样定义了一个
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();
//oc是一个可观察的集合,其中包含一些MyClass类型的项
cvs.Source=oc;
//什么是笨蛋?MyClass的属性
cvs.View.Filter=new谓词(输入=>(输入为MyClass).IsSelected==true);
//Major是MyClass的字符串属性
cvs.SortDescriptions.Add(新的SortDescription(
“主要”,列表或方向。升序);
但是我改变了代码,一切都解决了

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 cvs=new CollectionViewSource();
cvs.Source=oc;
cvs.SortDescriptions.Add(新的SortDescription(
“主要”,列表或方向。升序);
cvs.View.Filter=new谓词(输入=>(输入为MyClass).IsSelected==true);

有人知道路吗?

你应该问自己的第一件事是

为什么要将排序描述添加到CollectionViewSource 以及视图的过滤器?难道我不应该把这两个都加进去吗 同一个物体

答案是肯定的

要将筛选器逻辑直接添加到
CollectionViewSource
中,需要为
filter
事件添加事件处理程序

下面是一个例子

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;
        }
    }
}
显然,它正在覆盖您在视图上设置的过滤器


如果您仍然好奇,这里是。

我假设添加排序描述可能会影响视图属性(可能会创建一个新属性?),因此在第一种情况下,您向视图添加一个过滤器,然后排序描述的更改会有效地生成一个新视图?(另外,您的示例中有
cvs
cvs2
,因此这两种情况看起来都无关紧要……您可以在排序描述更改后快速检查cvs.View是否是同一个对象。否则,对CollectionViewSource是否有一些调用来使其无效,以及?
Predicate<object> filter;
if (FilterHandlersField.GetValue(this) != null)
{
    filter = FilterWrapper;
}
else
{
    filter = null;
}

if (view.CanFilter)
{
    view.Filter = filter;
}