第一种方法:

  后台:

 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. js简单校验form表单

    /** * 数据简单校验 */ function checkData (formId) { var check = true; var emailReg = new RegExp("^[a- ...

  2. SpringMVC入门(基于注解方式实现)

    ---------------------siwuxie095                             SpringMVC 入门(基于注解方式实现)         SpringMVC ...

  3. Hibernate查询方式(补)

    -----------------siwuxie095                             Hibernate 查询方式         1.对象导航查询     根据已经加载的对 ...

  4. 提交代码到远程GIT仓库,代码自动同步到远程服务器上。

    现在一般都会通过github,gitlab,gitee来管理我们的代码.我们希望只要我本地push了代码,远程服务器能自动拉取git仓库的代码,进行同步. 这就需要用到各仓库为我们提供的webhook ...

  5. maven的配置及仓库的配置

    1.maven的配置 1.1.注意:电脑上需要安装jdk. 1.2.配置MAVEN_HOME,再在path中配置到bin这一层. (1)配置MAVEN_HOME:我的电脑--->右击---> ...

  6. Qt中使用python--Hello Python!

    step1:install Python (version 2.7 or higher): step2:The configuration is as follows: 1.create qt con ...

  7. js导出到word、json、excel、csv

    tableExport.js ///*The MIT License (MIT) //Copyright (c) 2014 https://github.com/kayalshri/ //Permis ...

  8. 什么是adb命令?以及如果高效使用他们?

    接下来 我会为大家讲解 最通俗易懂的adb命令 希望大家能够喜欢...

  9. install pip(mac)

    simple method:  sudo easy_install pip you have done!and can install the other py programs using pip ...

  10. 2018.09.12 poj3621Sightseeing Cows(01分数规划+spfa判环)

    传送门 01分数规划板题啊. 发现就是一个最优比率环. 这个直接二分+spfa判负环就行了. 代码: #include<iostream> #include<cstdio> # ...