0

我刚刚ICollectionView在我的第一个 MVVM 项目中实现了一个,并且可以正常工作。不过,我认为实施可能会更好、更流畅。我将发布与我相关的代码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 命令绑定到 my 中MainView的按钮,数据显示在ListBox绑定到AdventurerFilter. 就像我之前伤心的那样,它有效,但我严重怀疑这不能更有效地完成。任何意见,将不胜感激!

编辑:我应该早点提到这一点,但Adventurers它是一个ObservableCollection.

4

1 回答 1

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();
}
于 2013-06-01T21:15:24.290 回答