WPF将枚举列表(或类似列表)绑定到复选框列表 [英] WPF binding Enum list (or similar) to list of checkboxes
问题描述
我想将复选框列表绑定到WPF中的枚举值的集合. 枚举不是[Flags].
I would like to bind a checkbox list to a collection of enum values in WPF. The enum is not [Flags].
上下文: 它用于过滤数据网格,其中每个项目都有我的枚举的实例. 它不一定需要绑定到List,也可以使用固定大小的List进行绑定.
Context: It is for filtering a datagrid, in which each item has a instance of my enum. It doesn't necessarily need to bind to an List, a fixed size collection of would work as well.
推荐答案
Assuming you want to bind to all possible values of your enum, you can do it with an ObjectDataProvider.
Declare this in your resources (Window.Resources
or App.Resources
etc.):
<ObjectDataProvider x:Key="enumValues" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:TestEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
这基本上表示对Enum.GetValues(typeof(TestEnum))
并将其公开为数据源.
注意:您需要在之前声明名称空间sys
和local
,其中sys
是clr-namespace:System;assembly=mscorlib
,而local
是枚举的名称空间.
This basically represents a call to Enum.GetValues(typeof(TestEnum))
and exposes it as a data source.
Note: You need to declare the namespaces sys
and local
before, where sys
is clr-namespace:System;assembly=mscorlib
and local
is the namespace of your enum.
一旦有了它,就可以像其他任何东西一样使用该ObjectDataProvider作为绑定源,例如:
Once you have that, you can use that ObjectDataProvider as a Binding source just like anything else, for example:
<ListBox ItemsSource="{Binding Source={StaticResource enumValues}}"/>
非声明性的方式只是在代码中分配它:
The non-declarative way of doing this is just assigning that in code:
someListBox.ItemsSource = Enum.GetValues(typeof(TestEnum));
不幸的是,为了绑定选定的项目,不能从Xaml设置SelectedItems属性,但是可以使用SelectionChanged事件:
For binding the selected items, unfortunately the SelectedItems property cannot be set from Xaml, but you can use the SelectionChanged event:
<ListBox Name="lb" ItemsSource="{Binding Source={StaticResource enumValues}}" SelectionMode="Multiple" SelectionChanged="lb_SelectionChanged"></ListBox>
,然后在发生以下情况的情况下在ViewModel(或您使用的任何对象)上设置属性:
and then set the property on your ViewModel (or whatever you use) in the event:
private void lb_SelectionChanged(object sender, SelectionChangedEventArgs e) {
viewModel.SelectedValues = lb.SelectedItems.OfType<TestEnum>().ToList();
}
这篇关于WPF将枚举列表(或类似列表)绑定到复选框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!