第一种方法:

  后台:

 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. 给出一个十六进制的数0xFF 0x80 (只有2“位”) 将其转换成有符号的一字节的十进制整数

    #include <stdio.h>#include<iostream>#include <stdlib.h>#include<string.h>usi ...

  2. [udemy]WebDevelopment_History of The Web

    WWW vs Internet For the begining, Internet was there. it was for the academics among universities Th ...

  3. docker搭建nginx

    在Docker下部署Nginx,包括: 部署一个最简单的Nginx,可以通过端口访问默认的网站 设置记录访问和错误日志的路径 以交互模式创建centos容器,如果本地没有镜像,会从仓库获取, 等待即可 ...

  4. Golang之Socket

    go创建socket很简单 package main import ( "fmt" "net" ) func main() { //服务器监听地址 fmt.Pr ...

  5. linux下nginx tomcat集群

    集群系统一般通过两台或多台节点服务器系统通过相应的硬件及软件互连,每个群集节点都是运行其自己进程的独立服务器. 这些进程可以彼此通信,对网络客户机来说就像是形成了一个单一系统,协同起来向用户提供应用程 ...

  6. Telnet 协议详解

    Telnet 协议详解 一.概述 ============================================================ Telnet 协议是 TCP/IP 协议族中 ...

  7. VS快捷键以及Reshaper快捷键

    VS快捷键: Resharper 快捷键(此图是保存他人的[具体是谁忘记了]): 参考: http://msdn.microsoft.com/zh-cn/library/da5kh0wa.aspx

  8. Basic4android v3.80 beta 发布

    增加了条件编译,共享模块,部分支持jar 文件直接访问.还有其他一些更新. I'm happy to release B4A v3.80 BETA. This version includes sev ...

  9. 2018.09.28 hdu5435A serious math problem(数位dp)

    传送门 数位dp卡常题. 写了一发dfs版本的发现过不了233. 于是赶紧转循环版本. 预处理出f数组. f[i][j]f[i][j]f[i][j]表示前i位数异或和为j的方案数. 然后每次直接数位d ...

  10. 2018.09.08 bzoj1151: [CTSC2007]动物园zoo(状压dp)

    传送门 状压dp好题啊. 可以发现这道题的状压只用压缩5位. f[i][j]表示当前在第i个位置状态为j的最优值. 显然可以由f[i-1]更新过来. 因此只用预处理在第i个位置状态为j时有多少个小朋友 ...