WPF:绑定/应用布尔属性筛选 [英] WPF: Bind/Apply Filter on Boolean Property
问题描述
我想一个过滤器应用到的ListBox
相应于 IsSelected
属性>复选框。
I want to apply a filter to a ListBox
accordingly to the IsSelected
property of a CheckBox
.
目前,我有这样的事情。结果
XAML
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 ...
}
它的工作原理,但这种解决方案感觉就像老式的方法(Windows窗体)。
It works but this solution feels like the old-fashioned way (Windows Forms).
问:结果
是否有可能与绑定实现这一/ XAML中?
Question:
Is it possible to achieve this with Bindings / in XAML?
感谢您的时间。
推荐答案
我能想到的唯一方法是使一个的ObjectDataProvider
和两个独立的<$ C $在XAML C> CollectionViewSource 的对象。一种观点将过滤器应用,其他的不会。然后,你可以直接绑定到的 CheckBox.IsChecked属性,并使用自定义的
的IValueConverter
。值变换器将有2依赖项属性 - 既键入 CollectionViewSource。
这些属性可以被称为 UnfilteredItems 的和 FilteredItems <的/ EM>。在XAML中,您将设置未经过滤的项目属性设置为 CollectionViewSource
这是未经过滤,将过滤的项目属性设置为一个具有过滤器。该转换器逻辑本身会如果是真的被简单 - ,返回过滤 CollectionViewSource
,如果为false,返回未经过滤的。
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.
这解决方案不是非常优雅,但它会完成这项工作。因为过滤器
不是的DependencyProperty
,并且只能由一个事件处理程序规定,我们的手是种系上这个。我不认为你的解决方案是一个坏女人,虽然。
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.
这篇关于WPF:绑定/应用布尔属性筛选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!