0

I have an ObservableCollection<MyObject> that is currently bound to a ListBox in my view. MyObject has an enum property which we'll call On and Off (among other properties). Using binding, is there a way to filter the collection and only display items that are on or off?

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Jason D
  • 2,634
  • 6
  • 33
  • 67

2 Answers2

3

You should have a look at CollectionViewSource and its filtering capabilities.

If you want to do the filtering in pure MVVM, you can have your viewmodel expose a property of type ICollectionView, apply whatever filter you want, and then bind to that property from XAML.

ViewModel:

public ICollectionView MyCollectionView { get; set; }

public ViewModel()
{
    var items = new List<string>
    {
        "Apple",
        "Orange"
    };

    MyCollectionView = CollectionViewSource.GetDefaultView(items);

    // Will only display items starting with "A".
    MyCollectionView.Filter = item => ((string)item).StartsWith("A");
}

XAML:

<ListBox ItemsSource="{Binding MyCollectionView}"/>
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
  • Is it possible to filter the `CollectionViewSource` in pure XAML or do you need code-behind? – Jason D Jun 01 '13 at 01:40
  • You can filter the collection in pure MVVM with no codebehind, by doing the filtering in the viewmodel. See my updated answer. – Adi Lester Jun 01 '13 at 13:27
  • This works. I'll have to play around with it some to fix a couple issues related to my code, but this certainly set me on the right track. Thanks! – Jason D Jun 01 '13 at 14:56
2

You might want to consider a collection view, or performing the filtering yourself within the view model.

devdigital
  • 34,151
  • 9
  • 98
  • 120
  • Is it possible to filter the `CollectionViewSource` in pure XAML or do you need code-behind? – Jason D Jun 01 '13 at 01:41
  • @DennisE: Sometimes it is easier not to, but anything you can do in XAML can be done in code-behind and vice-versa. – myermian Jun 01 '13 at 01:57
  • @DennisE: A simple search returns this... http://stackoverflow.com/questions/6461826/in-wpf-can-you-filter-a-collectionviewsource-without-code-behind – myermian Jun 01 '13 at 01:58
  • I tried that, but on the `` line, I get 2 errors. The first says "The member "Filter" is not recognized or is not accessible." The second says "Property 'Filter' does not have a value." – Jason D Jun 01 '13 at 02:01
  • Filter is an event (http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.filter.aspx), so if you set it in XAML the handler would be assumed to live in the code behind for that file. You should be considering the MVVM design pattern and minimising code behind, so have a look at the link provided in my answer to see how to filter in the view model. – devdigital Jun 01 '13 at 12:13