WPF: Bind/Apply Filter on Boolean Property

混江龙づ霸主 提交于 2019-12-11 12:00:01

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2693427/wpf-bind-apply-filter-on-boolean-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!