Enum 绑定到 CheckBox
第一种方法:
后台:
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的更多相关文章
- Asp.Net 将枚举类型(enum)绑定到ListControl(DropDownList)控件
在开发过程中一些状态的表示使用到枚举类型,那么如何将枚举类型直接绑定到ListControl(DropDownList)是本次的主题,废话不多说了,直接代码: 首先看工具类代码: /// <su ...
- WPF一组Radio与enum绑定
工作中用到了一组RadioButton对应一组数据的情况,这个时候最好能将一组RadioButton绑定Enum. 步骤 1.MyControl库中Type.cs中定义Enum namespace M ...
- Enum 绑定到 RadioButton
参考 这篇文章. 和 http://www.cnblogs.com/626498301/archive/2012/05/22/2512958.html
- wpf通过VisualTreeHelper找到控件内所有CheckBox和TextBox并做相应绑定
#region CheckBox与TextBox绑定 Dictionary<CheckBox, TextBox> CheckTextBoxDic = new Dictionary<C ...
- mysql的enum和set数据类型
定义一个ENUM或者SET类型,可以约束存入的数值. ENUM中的值必须是定义过数值列中的一个,比如ENUM('a','b','c'),存入的只能是'a'或者'b'或者'c',如果存入'','d'或者 ...
- C# MVC绑定 List<DapperRow>到bootstrap-table列表
1.Dapper返回List<dynamic>对象 /// <summary> /// 获取候选人推荐的分页数据 /// </summary> /// <pa ...
- checkbox全选与反选
用原生js跟jquery实现checkbox全选反选的一个例子 原生js: <!DOCTYPE html> <html lang="en"> <hea ...
- AngularJS系列:表单全解(表单验证,radio必选,三级联动,check绑定,form提交验证)
一.查看$scope -->寻找Form控制变量的位置 Form控制变量 格式:form的name属性.input的name属性.$... formName.inputField.$pristi ...
- WPF 界面如何绑定Command
WPF中,我们使用MVVM,在ViewModel中定义Command和其业务逻辑,界面绑定Command. 那么是不是所有的事件都可以定义Command呢,然后将业务全部放在ViewModel中呢? ...
随机推荐
- 安装Ubuntu后一些准备
一些基础 安装的时候,先不选镜像就可以避开简易安装. 更改root密码:sudo passwd root 更改源,更新,不行就打断在更新 安装vim 改为unity模式,安装VMware Tools, ...
- My97DatePicker 日历控件
My97DatePicker 是一款非常强大的日历控件,使用也非常简单,也能修改源码,牛逼我就不吹了,自己用用看 使用 1.引入 <script language="javascrip ...
- oracle 将逗号分隔的字符串转成多行记录
, rownum), length(, rownum, length(replace('a,b,c,d', ',', '')), length('a,b,c,d') from dual connect ...
- 编辑距离12 · Edit Distance12
[抄题]: 给出两个单词word1和word2,计算出将word1 转换为word2的最少操作次数. 你总共三种操作方法: 插入一个字符 删除一个字符 替换一个字符 [思维问题]: [一句话思路]: ...
- fragment 事务回滚 ---动态创建fragment
import java.util.Date; import java.util.LinkedList; import com.qianfeng.gp08_day23_fragment5.fragmen ...
- Bad Hair Day
/* Some of Farmer John's N cows (1 ≤ N ≤ 80,000) are having a bad hair day! Since each cow is self-c ...
- 第三章 RNA测序
第三章 RNA测序 RNA测序(RNA Sequencing,简称RNA-Seq,也被称为全转录物组鸟枪法测序Whole Transcriptome Shotgun Sequencing,简称WT ...
- Debian 采用 iso 镜像作为 apt 源
1.将N个debian-506-amd64-DVD-N.iso存放于本地或其他媒介内,本例是放在本机/iso/目录下2.创建N个挂载点目录 如下: debian:~#mkdir –r /media/d ...
- c++11多线程学习笔记之四 生产消费者
#ifndef MY_QUEUE_H__ #define MY_QUEUE_H__ #include<list> #include<mutex> #include<thr ...
- 7.25 js 自定义方法 a.b
调用: $(function(){ Starinput.initiate({name:'qr1_z.startlevel',tar: $("#sitelogo1"), stars: ...