WPF将枚举列表(或类似列表)绑定到复选框列表 [英] WPF binding Enum list (or similar) to list of checkboxes

查看:301
本文介绍了WPF将枚举列表(或类似列表)绑定到复选框列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将复选框列表绑定到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)) 并将其公开为数据源. 注意:您需要在之前声明名称空间syslocal,其中sysclr-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆