Enum Binding ItemsSource In WPF
在WPF中枚举绑定到ItemsSource。
一、通过ObjectDataProvider 获取Enum数据源
首先我们定义一个Enum类:
public enum TableSelectedType
{
SelectedOne,
SelectedTwo,
SelectedThird
}
接着在Xaml中的Resource里定义数据源。
<UserControl.Resources>
<ObjectDataProvider x:Key="odp" MethodName="GetNames" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:TableSelectedType"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</UserControl.Resources>
我们这里写好了一个Enum数据源,他的key是odp。我们把它绑定到ComboBox的ItemsSource上看下。
<ComboBox ItemsSource="{Binding Source={StaticResource odp}}"/>
效果图:
但是有时候,我们要绑定的是Enum,但想显示它相应的中文字符串。比如“SelectOne”显示为“第一条”。
这里我用到了转换器(Converter).

代码
xaml中:

代码
效果:
二、通过Dictionary来存Enum,并绑定到ItemsSource上
这种方便且效率高。我们还是用上面的Enum类型。我们声明一个Dictionary的属性TableSelectedTypeCollection ,并对他初始话。
public partial class ConboBoxEnum : UserControl
{
public ConboBoxEnum()
{
InitializeComponent();
TableSelectedTypeCollection=new Dictionary<TableSelectedType, string>();
TableSelectedTypeCollection.Add(TableSelectedType.SelectedOne,"第一条");
TableSelectedTypeCollection.Add(TableSelectedType.SelectedTwo,"第二条");
TableSelectedTypeCollection.Add(TableSelectedType.SelectedThird,"第三条");
this.DataContext = this;
}
public Dictionary<TableSelectedType, string> TableSelectedTypeCollection { get; set; }
}
Xaml中,我们用TableSelectedTypeCollection 来绑定ComboBox的ItemsSource。
<ComboBox ItemsSource="{Binding TableSelectedTypeCollection}" SelectedValue="{Binding TableSelectedType}" DisplayMemberPath="Value"/>
这里我们用Value来显示它对应的中文字。SelectedValue来绑定它的Enum类型。因为后台我们通常用Enum中的类型。
作者: Lee's Blog 发表于 2011-08-17 23:24 原文链接
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架