第一种方法:

  后台:

 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. UpdatePanel中弹出新窗口

    如果允许,在UpdatePanel中使用iframe即可,不允许的话,用下面的方法实现弹窗 要在UpdatePanel中使用FileUpload时,会遇到此问题,或者同类其它情况 <asp:Sc ...

  2. jDeveloper运行慢

    最近在使用 Jdeveloper 10.1.3.3 版本时发现速度奇慢无比,后经Google,发现如下解决方案:在 jdev.conf 文件的末尾加上如下两行,速度即可得到显著的提高. AddVMOp ...

  3. mysql自定义函数收集

    代码: 查找字符串 in_string 中,存在多少个字符串 in_find_str delimiter $$ DROP FUNCTION IF EXISTS `fn_findCharCount` $ ...

  4. hreeJS加载Obj资源后如何实现内存释放?

    问题: 我利用ThreeJS做了一个在同一个场景下动态加载Obj的页面,具体功能是:点击按钮A:加载A模型,点击按钮B:加载B模型...现在的问题是,前面已经加载过的模型,无法实现释放,内存一直在累加 ...

  5. Spark cache、checkpoint机制笔记

    Spark学习笔记总结 03. Spark cache和checkpoint机制 1. RDD cache缓存 当持久化某个RDD后,每一个节点都将把计算的分片结果保存在内存中,并在对此RDD或衍生出 ...

  6. 07 Maven 使用Nexus创建私服

    7. Maven 使用Nexus创建私服 私服不是 Maven 的核心概念,它仅仅是一种衍生出来的特殊的 Maven 仓库.通过建立自己的私服,就可以降低中央仓库负荷.节省外网带宽.加速 Maven ...

  7. ubuntu系统下安装pyspider:搭建pyspider服务器新手教程

    首先感谢“巧克力味腺嘌呤”的博客和Debian 8.1 安装配置 pyspider 爬虫,本人根据他们的教程在ubuntu系统中进行了实际操作,发现有一些不同,也出现了很多错误,因此做此教程,为新手服 ...

  8. css心得体会

    非块级元素  要使得其有长宽的效果  可以设置  margin  和  padding 块级元素     可以直接设置  width  和  height div标签   要使得你内部元素居中   可 ...

  9. C语言之计算字符串最后一个单词的长度,单词以空格隔开

    //计算字符串最后一个单词的长度,单词以空格隔开. #include<stdio.h> #include<string.h> #include<windows.h> ...

  10. IntelliJ IDEA 2017版 导入项目项目名称为红色

    1.导入的项目全部是红色的,原因是版本控制问题,所以修改如下:(File--->settings) 2.找到如图位置的字样,选中当前项目,选择铅笔位置 选择铅笔 弹出对话框(默认选择的是proj ...