有效地实现ICollectionView进行过滤

时间:2013-06-01 19:39:28

标签: c# mvvm filtering icollectionview

我刚刚在我的第一个MVVM项目中实现了一个ICollectionView,我让它工作了。不过,我认为实施可能更好,更流畅。我会发布与我的ICollectionView相关的代码,如果有人可以就如何简化或改进它给我任何提示或建议,请告诉我。这是我的代码:

private ICollectionView _advFilter;

public ICollectionView AdventurerFilter
{
    get { return _advFilter; }
    set
    {
        if (_advFilter != value)
        {
            _advFilter = value;
            RaisePropertyChanged(() => AdventurerFilter);
        }
    }
}


public MainViewModel()
{
    AdvNoFilter();
}


public void LoadGameExecute()
{
    //Serialization Logic

    AdvNoFilter();
}

public void ShowAllExecute()
{
    AdvNoFilter();
}

public void ShowEmployedExecute()
{
    AdvFilter(AdvStatus.Employed);
}

public void ShowAvailableExecute()
{
    AdvFilter(AdvStatus.Available);
}


void AdvFilter(AdvStatus status)
{
    AdventurerFilter = CollectionViewSource.GetDefaultView(Adventurers);
    AdventurerFilter.Filter = adv => ((Adventurer)adv).Status.Equals(status);
}

void AdvNoFilter()
{
    AdventurerFilter = CollectionViewSource.GetDefaultView(Adventurers);
    AdventurerFilter.Filter = null;
}

所有这些都在我的MainViewModel中。 Show ... Execute命令绑定到MainView中的按钮,数据显示在ListBox中,绑定到AdventurerFilter。就像我以前悲伤一样,它有效,但我很怀疑这不能更有效地完成。任何建议将不胜感激!

编辑:我之前应该提到这一点,但AdventurersObservableCollection

1 个答案:

答案 0 :(得分:1)

此代码不是ICollectionView实现。它只使用通过CollectionViewSource.GetDefaultView获得的默认实现。

您可以缓存获取的ICollectionView,每次要更改过滤器时都无需分配它:

private ICollectionView _advFilter;

public MainViewModel()
{
    // assuming that Adventurers is ObservableCollection<Adventurer>
    _advFilter = CollectionViewSource.GetDefaultView(Adventurers);

    AdvNoFilter();
}

public void ShowEmployedExecute()
{
    AdvFilter(AdvStatus.Employed);
}

public void ShowAvailableExecute()
{
    AdvFilter(AdvStatus.Available);
}

void AdvFilter(AdvStatus status)
{
    _advFilter.Filter = adv => ((Adventurer)adv).Status.Equals(status);
    _advFilter.Refresh();
}

void AdvNoFilter()
{
    _advFilter.Filter = null;
    _advFilter.Refresh();
}