Question

I just implemented an ICollectionView into my first MVVM project and I have it working. I think, though, that the implementation could be better and more fluid. I'll post the code relating to my ICollectionView and if anybody can give me any tips or suggestions on how to streamline or improve it, please let me know. Here's my code:

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;
}

All of this is in my MainViewModel. The Show...Execute commands are bound to buttons in my MainView and the data is displayed in a ListBox, which is bound to AdventurerFilter. Like I sad before, it works, but I seriously doubt this could not be done more efficiently. Any advice would be appreciated!

EDIT: I should have mentioned this earlier but Adventurers is an ObservableCollection.

Was it helpful?

Solution

This code isn't an implementation of ICollectionView. It just uses default implementation, obtained through CollectionViewSource.GetDefaultView.

You can cache obtained ICollectionView, there's no need to assign it every time you want to change the filter:

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top