views:

127

answers:

1

I want to apply a filter to a ListBox accordingly to the IsSelected property of a CheckBox.

At the moment I have something like this.
XAML

<CheckBox Name="_filterCheckBox" Content="Filter list" Checked="ApplyFilterHandler"/>
<ListBox ItemsSource="{Binding SomeItems}" />

CodeBehind

    public ObservableCollection<string> SomeItems { get; private set; }

    private void ApplyFilterHandler(object sender, RoutedEventArgs e)
    {
        if (_filterCheckBox.IsChecked.Value)
            CollectionViewSource.GetDefaultView(SomeItems).Filter += MyFilter;
        else
            CollectionViewSource.GetDefaultView(SomeItems).Filter -= MyFilter;
    }

    private bool MyFilter(object obj)
    {
        return ...
    }

It works but this solution feels like the old-fashioned way (Windows Forms).

Question:
Is it possible to achieve this with Bindings / in XAML?

Thanks for your time.

A: 

The only way I can think of would be to make an ObjectDataProvider and two separate CollectionViewSource objects in XAML. One view would have the filter applied, the other would not. Then you could bind directly to the CheckBox.IsChecked property and use a custom IValueConverter. The value converter would have 2 dependency properties- both of type CollectionViewSource. These properties might be called, "UnfilteredItems" and "FilteredItems." In XAML, you would set the unfiltered items property to the CollectionViewSource that was unfiltered, and the filtered items property to the one with the filter. The converter logic itself would be simple- if true, return the filtered CollectionViewSource, if false, return the unfiltered one.

This solution is not extremely elegant, but it would get the job done. Because Filter is not a DependencyProperty and can only be specified by an event-handler, our hands are kind of tied on this one. I don't think your solution is a bad one, though.

Charlie