2010-04-22 62 views
1

我想对ListBox应用过滤器,因此CheckBoxIsSelected属性相应。WPF:在布尔属性上绑定/应用过滤器

此刻我有这样的事情。
XAML

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

代码隐藏

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

它的工作原理,但这种解决方案感觉就像老式的方法(Windows窗体)。

问题:
是否有可能用Bindings /在XAML中实现这一点?

谢谢你的时间。

回答

0

我能想到的唯一方法是在XAML中制作ObjectDataProvider和两个单独的CollectionViewSource对象。一种观点会应用过滤器,另一种则不会。然后,您可以直接绑定到CheckBox.IsChecked属性并使用自定义IValueConverter。值转换器将具有2个依赖项属性 - 类型为CollectionViewSource.可能会调用这些属性,“未筛选项目”和“FilteredItems”。在XAML中,您可以将未过滤的项目属性设置为未过滤的CollectionViewSource,并将已过滤的项目属性设置为具有过滤器的项目属性。转换器逻辑本身会很简单 - 如果为true,则返回已过滤的CollectionViewSource,如果为false,则返回未过滤的。

该解决方案不是非常优雅,但它会完成工作。因为Filter不是DependencyProperty并且只能由事件处理程序指定,所以我们的手在这一个上绑定。不过,我认为你的解决方案并不好。