Collectionviewsource过滤方法

时间:2017-10-03 11:59:04

标签: c# wpf mvvm data-binding

我为我的应用程序遵循MVVM模型,我有一个文本框,作为过滤集合的输入。我理解使用lambda表达式的observablecollection过滤器,但我无法理解collectionviewsource方法。我该如何使用它实现collectionviewsource方法。

这是我的viewmodel类:

private ObservableCollection<SPFetchCREntity> _CRmappings2 = new ObservableCollection<SPFetchCREntity>();
public ObservableCollection<SPFetchCREntity> CRmappings2
{
    get { return _CRmappings2; }
    set
    {
        _CRmappings2 = value;
        RaisePropertyChanged("CRmappings2");
    }
}

public ICollectionView AllCRSP


{ get; private set;}



public void UpdatePopList()
{
   CRmappings2 = new ObservableCollection<SPFetchCREntity>(crentities.Where(p => p.MU_Identifier == selectmu.ToString()).ToList()); 
}

1 个答案:

答案 0 :(得分:1)

绑定到ICollectionView并过滤此内容:

public void UpdatePopList()
{
    CRmappings2 = new ObservableCollection<SPFetchCREntity>(crentities.ToList());
    AllCRSP = CollectionViewSource.GetDefaultView(CRmappings2);
    AllCRSP.Filter = obj =>
    {
        SPFetchCREntity entity = obj as SPFetchCREntity;
        return entity != null && entity.MU_Identifier == selectmu.ToString();
    };
}

private string _selectmu;
public string Selectmu
{
    get { return _selectmu; }
    set { _selectmu = value; AllCRSP.Refresh(); } //<-- refresh the ICollectionView whenever the selectmu property gets set or when you want to refresh the filter
}