• Enum Binding ItemsSource In WPF


    在WPF中枚举绑定到ItemsSource。 一、通过ObjectDataProvider 获取Enum数据源 首先我们定义一个Enum类: public enum TableSelectedType { SelectedOne, SelectedTwo, SelectedThird } 接着在Xaml中的Resource里定义数据源。 我们这里写好了一个Enum数据源,他的key是odp。我们把它绑定到ComboBox的ItemsSource上看下。 效果图: image 但是有时候,我们要绑定的是Enum,但想显示它相应的中文字符串。比如“SelectOne”显示为“第一条”。 这里我用到了转换器(Converter). 代码 xaml中: 代码 效果: image 二、通过Dictionary来存Enum,并绑定到ItemsSource上 这种方便且效率高。我们还是用上面的Enum类型。我们声明一个Dictionary的属性TableSelectedTypeCollection ,并对他初始话。 public partial class ConboBoxEnum : UserControl { public ConboBoxEnum() { InitializeComponent(); TableSelectedTypeCollection=new Dictionary(); TableSelectedTypeCollection.Add(TableSelectedType.SelectedOne,"第一条"); TableSelectedTypeCollection.Add(TableSelectedType.SelectedTwo,"第二条"); TableSelectedTypeCollection.Add(TableSelectedType.SelectedThird,"第三条"); this.DataContext = this; } public Dictionary TableSelectedTypeCollection { get; set; } } Xaml中,我们用TableSelectedTypeCollection 来绑定ComboBox的ItemsSource。 这里我们用Value来显示它对应的中文字。SelectedValue来绑定它的Enum类型。因为后台我们通常用Enum中的类型。 效果还是一样。 image 三、通过特性(Attribute)来获取 这里用到了MS命名空间下的using System.ComponentModel;在枚举元素上加Description这个特性。 public enum TableSelectedType { [Description("选择第一行")] SelectedOne, [Description("选择第二行")] SelectedTwo, [Description("选择第三行")] SelectedThird } 我们写一个EnumHelper来获取它。 public static class EnumHelper { public static T GetEnumAttribute(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(source); if (str==null) return null; return str.Description; } } 然后我们在实例化这个枚举的时候,调用它就可以。 public Dictionary TableSelectedTypeDictionary { get; set; } public ConboBoxEnum() { InitializeComponent(); TableSelectedTypeDictionary=new Dictionary(); 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; }
  • 相关阅读:
    BigDecimal加减乘除计算方式
    Element-UI 关于table中fixed使用和table样式混乱问题处理
    java集合框架中contains(),containsKey()和containsValue()的用法
    Vue中子组件watch监听props中父组件对象的变化的坑
    js中使用splice在一次循环删除数组中的多个元素
    Java中instanceof关键字的理解
    List.contains(Object object)方法,比较对象是否相同
    Vue 动态路由的实现以及 Springsecurity 按钮级别的权限控制
    sql中#与$的区别
    Vue自定义指令实现按钮级权限控制功能
  • 原文地址:https://www.cnblogs.com/sjqq/p/6946011.html
Copyright © 2020-2023  润新知