Can I filter a collection from xaml?

Relativity picture Relativity · Feb 7, 2011 · Viewed 15k times · Source

I have a wpf-mvvm application.

I have an observable collection in my viewmodel

public ObservableCollection<BatchImportResultMessageDto> ImportMessageList { get; set; } 

"BatchImportResultMessageDto" contains two properties..

result type..and message. Result type can be success or failure.

I need to display success in one list box ..and failure in another listbox.

I can do this..by having 2 observable collections in viewmodel to hold success/failure.

public ObservableCollection<BatchImportResultMessageDto> ImportFailureMessageList { get; set; } // To hold the failure messages.
public ObservableCollection<BatchImportResultMessageDto> ImportSuccessMessageList { get; set; } // To hold the sucess messages.

But is there any other better way so that i can filter it (without new two collections) ?

Answer

devdigital picture devdigital · Feb 7, 2011

You can use a CollectionViewSource and make it a property of your view model, and bind to that instead of your ImportMessageList collection directly from the XAML. Set your ImportMessageList collection as the Source of the CollectionViewSource, and then configure a predicate to do your filtering on the CollectionViewSource.

Something like:

private ICollectionView messageListView;
public ICollectionView MessageListView
{
    get { return this.messageListView; }
    private set
    {
      if (value == this.messageListView)
      {
        return;
      }

      this.messageListView = value;
      this.NotifyOfPropertyChange(() => this.MessageListView);
    }
}

...


this.MessageListView = CollectionViewSource.GetDefaultView(this.ImportMessageList);
this.MessageListView.Filter = new Predicate<object>(this.FilterMessageList);

...

public bool FilterMessageList(object item)
{
  // inspect item as message here, and return true 
  // for that object instance to include it, false otherwise
  return true;
}