第一种方法:

  后台:

 internal static class EnumCache<T>
where T : struct, IConvertible
{
private static Dictionary<int, Tuple<T, string>> collectionCache; public static Dictionary<int, Tuple<T, string>> CollectionCache
{
get
{
if (collectionCache == null)
{
collectionCache = CreateCache();
}
return collectionCache;
}
} private static Dictionary<int, Tuple<T, string>> CreateCache()
{
Dictionary<int, Tuple<T, string>> collectionCache = new Dictionary<int, Tuple<T, string>>(); var fields = typeof(T).GetFields().Where(x => x.IsLiteral); foreach (var field in fields)
{
var intValue = (int)field.GetValue(null);
var displayText = ((DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false))[].Description;
T operatorEnum = (T)(object)field.GetValue(null);
var tuple = Tuple.Create(operatorEnum, displayText);
collectionCache.Add(intValue, tuple);
}
return collectionCache;
}
} public class LogicalOperatorEnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//this is a hack, binding is unbinding to text i think???
if (value is string)
{
value = LogicalOperator.Where;
} return EnumCache<LogicalOperator>.CollectionCache[(int)value].Item2;
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var displayText = (String)value;
var key = EnumCache<LogicalOperator>.CollectionCache.Single(x => x.Value.Item2 == displayText).Key;
return (object)EnumCache<LogicalOperator>.CollectionCache[key].Item1;
}
}

前台:

<templates:LogicalOperatorEnumConverter x:Key="LogicalOperatorEnumConverter" />
<ComboBox ToolTip="The logical operator" Grid.Column="1" Margin="2 0 0 0" ItemsSource="{Binding LogicalOperators}" SelectedItem="{Binding LogicalOperator, Mode=TwoWay}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=. , Converter={StaticResource LogicalOperatorEnumConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

此方法为泛型方法封装,每次用时,都要写一个转换器,如:LogicalOperatorEnumConverter 。

第二种方法:

  写一个固定的类:

    

 public class ComboBoxDataModel : BaseEntity
{
private Guid _id;
public Guid ID { get => _id; set => SetProperty(ref _id, value); }
private string value; public string Value
{
get { return value; }
set { this.value = value; OnPropertyChanged("Value"); }
}
private string text; public string Text
{
get { return text; }
set { this.text = value; OnPropertyChanged("Text"); }
}
private bool isChecked;
public bool IsChecked
{
get { return isChecked; }
set { this.isChecked = value; OnPropertyChanged("IsChecked"); }
} }

将Enum转成ObservableCollection<ComboBoxDataModel>


/// <summary>
/// 枚举转换为List,显示名称为summary
/// </summary>
/// <param name="pEnum"></param>
/// <param name="pShowEnumValue">True:返回的是0,1,2等值;False:返回的是值对于的枚举项目名称</param>
/// <returns></returns>

public static ObservableCollection<ComboBoxDataModel> GetEnumList(Type pEnumType, bool pShowEnumValue = true)
{
ObservableCollection<ComboBoxDataModel> list = new ObservableCollection<ComboBoxDataModel>();
Type typeDescription = typeof(DescriptionAttribute);
System.Reflection.FieldInfo[] fields = pEnumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
if (pShowEnumValue)
{
strValue = ((int)pEnumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
}
else
{
strValue = pEnumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null).ToString();
}
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > )
{
DescriptionAttribute aa = (DescriptionAttribute)arr[];
strText = aa.Description;
}
else
{
strText = field.Name;
}
list.Add(new ComboBoxDataModel() { Text = strText, Value = strValue });
}
}
return list;
}

ViewModel:

 private ObservableCollection<ComboBoxDataModel> _enumBusinessPartDiscountTypeList;
//数量范围列表
public ObservableCollection<ComboBoxDataModel> EnumBusinessPartDiscountTypeList
{
get => _enumBusinessPartDiscountTypeList;
set
{
SetProperty(ref _enumBusinessPartDiscountTypeList, value);
}
} ctor中
EnumBusinessPartDiscountTypeList =
ComboBoxListHelper.GetEnumList(typeof(EnumBusinessPartDiscountType), true);

前台:

 <ComboBox x:Name="cmbQuantitativeRange" Grid.Row="0" Grid.Column="3" DisplayMemberPath="Text" SelectedValuePath="Value"  Margin="5" Height="25"
ItemsSource="{Binding EnumBusinessPartDiscountTypeList}"
SelectedItem="{Binding SelectedEnumBusinessPartDiscountType,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
</ComboBox>

这种方式也可以,但需要写更多的代码,项目一开始用的是第二种。后来发现第一种,感觉第一种更比较好理解点。主要还是看项目需求,来选择。

Enum 绑定到 CheckBox的更多相关文章

  1. Asp.Net 将枚举类型(enum)绑定到ListControl(DropDownList)控件

    在开发过程中一些状态的表示使用到枚举类型,那么如何将枚举类型直接绑定到ListControl(DropDownList)是本次的主题,废话不多说了,直接代码: 首先看工具类代码: /// <su ...

  2. WPF一组Radio与enum绑定

    工作中用到了一组RadioButton对应一组数据的情况,这个时候最好能将一组RadioButton绑定Enum. 步骤 1.MyControl库中Type.cs中定义Enum namespace M ...

  3. Enum 绑定到 RadioButton

    参考 这篇文章. 和 http://www.cnblogs.com/626498301/archive/2012/05/22/2512958.html

  4. wpf通过VisualTreeHelper找到控件内所有CheckBox和TextBox并做相应绑定

    #region CheckBox与TextBox绑定 Dictionary<CheckBox, TextBox> CheckTextBoxDic = new Dictionary<C ...

  5. mysql的enum和set数据类型

    定义一个ENUM或者SET类型,可以约束存入的数值. ENUM中的值必须是定义过数值列中的一个,比如ENUM('a','b','c'),存入的只能是'a'或者'b'或者'c',如果存入'','d'或者 ...

  6. C# MVC绑定 List<DapperRow>到bootstrap-table列表

    1.Dapper返回List<dynamic>对象 /// <summary> /// 获取候选人推荐的分页数据 /// </summary> /// <pa ...

  7. checkbox全选与反选

    用原生js跟jquery实现checkbox全选反选的一个例子 原生js: <!DOCTYPE html> <html lang="en"> <hea ...

  8. AngularJS系列:表单全解(表单验证,radio必选,三级联动,check绑定,form提交验证)

    一.查看$scope -->寻找Form控制变量的位置 Form控制变量 格式:form的name属性.input的name属性.$... formName.inputField.$pristi ...

  9. WPF 界面如何绑定Command

    WPF中,我们使用MVVM,在ViewModel中定义Command和其业务逻辑,界面绑定Command. 那么是不是所有的事件都可以定义Command呢,然后将业务全部放在ViewModel中呢? ...

随机推荐

  1. 【校招面试 之 C/C++】第16题 C++ new和delete的实现原理

    1.new new操作针对数据类型的处理,分为两种情况: (1)简单数据类型(包括基本数据类型和不需要构造函数的类型) 代码实例: int* p = new int; 汇编码如下: int* p = ...

  2. 合并区间 · Merge Intervals & 插入区间 · Insert Interval

    [抄题]: 给出若干闭合区间,合并所有重叠的部分. 给出的区间列表 => 合并后的区间列表: [ [ [1, 3], [1, 6], [2, 6], => [8, 10], [8, 10] ...

  3. memcache简单操作

    <?php $m = new Memcache(); $m->connect('localhost',11211); //获取版本 echo "server's version: ...

  4. Castle ActiveRecord学习(五)使用HQL语句查询

    来源:http://www.cnblogs.com/Terrylee/archive/2006/04/12/372823.html 一.HQL简单介绍HQL全名是Hibernate Query Lan ...

  5. Luogu 3960 [NOIP2017] 列队 - splay|线段树

    题解 是我从来没有做过的裂点splay... 看的时候还是很懵逼的QAQ. 把最后一列的$n$个数放在一个平衡树中, 有 $n$ 个点 剩下的$n$行数, 每行都开一个平衡树,开始时每棵树中仅有$1$ ...

  6. code4906 删数问题

    题目: 键盘输入一个高精度的正整数n(<=240位), 去掉任意s个数字后剩下的数字按原左右次序将组成一个新的正整数. 编程对给定的n和s,寻找一种方案,使得剩下的数最小. Simple Inp ...

  7. jsp 页面 摘要, 要截取字符串 ,当时 字符串中包含 html标签,截取后无法显示

    如题: 处理办法: 1.  使用struts标签 <s:property  value ="#text.replaceAll('<[^>]+>','').substr ...

  8. 1、GDB程序调试

    GDB是GNU开源组织发布的一个强大的Linux下的程序调试工具.一般来说GDB主要完成下面四个部分的功能. 1)启动你的程序,可以按照你的自定义的要求运行程序. 2)可让被调试程序在你所指定的调试的 ...

  9. 2018.08.27 rollcall(非旋treap)

    描述 初始有一个空集,依次插入N个数Ai.有M次询问Bj,表示询问第Bj个数加入集合后的排名为j的数是多少 输入 第一行是两个整数N,M 接下来一行有N个整数,Ai 接下来一行有M个整数Bj,保证数据 ...

  10. hdu-1141

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1141 参考文章:https://blog.csdn.net/fei____fei/article/de ...