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

代码public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string[] enmus = value as string[];
List<string> result=new List<string>();
foreach (var item in enmus)
{
switch (item)
{
case "SelectedOne":
result.Add("第一行");
break;
case "SelectedTwo":
result.Add("第二行");
break;
case "SelectedThird":
result.Add("第三行");
break;
}
}
return result;
}

xaml中:

代码 <ComboBox ItemsSource="{Binding Source={StaticResource odp}, Converter={StaticResource EnumTypeToStringConverter}}"/>

效果:

二、通过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中的类型。

效果还是一样。  

三、通过特性(Attribute)来获取

这里用到了MS命名空间下的using System.ComponentModel;在枚举元素上加Description这个特性。

 public enum TableSelectedType
{
[Description("选择第一行")]
SelectedOne,
[Description("选择第二行")]
SelectedTwo,
[Description("选择第三行")]
SelectedThird
}

我们写一个EnumHelper来获取它。

 public static class EnumHelper
{
public static T GetEnumAttribute<T>(Enum source)where T:Attribute
{
Type type = source.GetType();
var sourceName = Enum.GetName(type, source);
FieldInfo field = type.GetField(sourceName);
object[] attributes = field.GetCustomAttributes(typeof (T), false);
foreach (var o in attributes)
{
if (o is T)
return (T) o;
}
return null;
} public static string GetDescription(Enum source)
{
var str = GetEnumAttribute<DescriptionAttribute>(source);
if (str==null)
return null;
return str.Description;
} }

然后我们在实例化这个枚举的时候,调用它就可以。

 public Dictionary<TableSelectedType, string> TableSelectedTypeDictionary { get; set; }
public ConboBoxEnum()
{
InitializeComponent(); TableSelectedTypeDictionary=new Dictionary<TableSelectedType, string>();
TableSelectedTypeDictionary.Add(TableSelectedType.SelectedOne, EnumHelper.GetDescription(TableSelectedType.SelectedOne));
TableSelectedTypeDictionary.Add(TableSelectedType.SelectedTwo, EnumHelper.GetDescription(TableSelectedType.SelectedTwo));
TableSelectedTypeDictionary.Add(TableSelectedType.SelectedThird, EnumHelper.GetDescription(TableSelectedType.SelectedThird)); this.DataContext = this;
}

Enum Binding ItemsSource In WPF的更多相关文章

  1. Listbox Binding ItemsSource

    把List<CourseItem>绑定到ListBox. 前台绑定: <ListBox x:Name="ItemBox" Grid.Row="1&quo ...

  2. Impossible WPF Part 2: Binding Expressions

    原文 http://www.11011.net/wpf-binding-expressions Back in April I posted an idea for building an expre ...

  3. WPF自学入门(七)WPF 初识Binding

    今天记录一下Binding的基础和具体的使用方法,说起这个Binding,在WPF中,Binding是很重要的特征,在传统的Windows软件来看,大多数都是UI驱动程序的模式,也可以说事件驱动程序, ...

  4. WPF Binding ElementName方式无效的解决方法--x:Reference绑定

    原文:WPF Binding ElementName方式无效的解决方法--x:Reference绑定 需求: 背景:Grid的有一个TextBlock name:T1和一个ListBox,ListBo ...

  5. WPF自定义控件与样式(8)-ComboBox与自定义多选控件MultComboBox

    一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要内容: 下拉选 ...

  6. WPF仿Word头部格式,涉及DEV RibbonControl,NarvbarControl,ContentPresenter,Navigation

    时隔1个月,2015/06/17走进新的环境. 最近一个星期在学习仿Word菜单栏的WPF实现方式,废话不多说,先看一下效果. 打开界面后,默认选中[市场A],A对应的菜单栏,如上图, 选择[市场B] ...

  7. WPF快速精通版

    命名空间: xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:U ...

  8. WPF DataGrid显格式

    Guide to WPF DataGrid formatting using bindings Peter Huber SG, 25 Nov 2013 CPOL    4.83 (13 votes) ...

  9. 【转】WPF自定义控件与样式(8)-ComboBox与自定义多选控件MultComboBox

    一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等. 本文主要内容: 下拉选择控件ComboBox的自定义样式及扩展: 自定义多选控件Mul ...

随机推荐

  1. 使用 C#的 is 和 as 操作符来转型

    在 C#语言中进行类型转换的另一种方式是使用 is 操作符. is 检查一个对象是否兼容于指定的类型,并返回一个 Boolean 值: true 或 false.注意 is 操作符永远不会抛出异常,以 ...

  2. active admin

    activeadmin 1.0.0.pre4 所依赖的库 gem 'jquery-rails', '~> 4.0.4' 4.2版本会出现找不到jquery-ui 的datepicker错误 使用 ...

  3. 导入Frameworks 死活引用不Liao头文件

    向工程中拖入或add file时可能会出现Frameworks导入,但是在添加该Frameworks后却引用不到相应的头文件 打开工程文件目录发现frameworks所在的路径并不存在,而是直接在工程 ...

  4. UIPageControl修改圆点大小,根据View大小自适应

    遇到了个基本的控件问题,当设置UIPageControl的frame很小时,上面的小圆点会忽视view的frame而将圆点显示到控件外面. 但是如果想要设置小一点的圆点,或改变圆点间的间距,从而实现自 ...

  5. $Android设置TextView的字体

    做项目的时候,需要使用到手写字体来让内容更加的美观.可是程序中默认使用的是系统的默认字体,怎么将TextView(或EditText)的字体设置成自己想要的字体呢?步骤如下: 1.下载字体文件(.tt ...

  6. [原创]spring及springmvc精简版--IOC

    本篇博客为自己学习spring和springmvc的一个总结.主要以代码为主,至于文字性描述理解性东西,可以自行百度.有认识不妥的地方,还望指出,相互学习. 以前很困惑spring中的一些概念,在学习 ...

  7. Android相机实时自动对焦的完美实现

    https://zhidao.baidu.com/question/873328177698804372.html Android相机实时自动对焦的完美实现 http://blog.csdn.net/ ...

  8. PHP封装时间类

    开发中经常用到时间的一些操作,比如昨天,今天,前天,近七天,一周等等. class time{ private $year;//年 private $month;//月 private $day;// ...

  9. CSS3手风琴菜单 可同时折叠多个菜单

    在线演示 本地下载

  10. HDU 3449 Consumer

    这是一道依赖背包问题.背包问题通常的解法都是由0/1背包拓展过来的,这道也不例外.我最初想到的做法是,由于有依赖关系,先对附件做个DP,得到1-w的附件背包结果f[i]表示i花费得到的最大收益,然后把 ...