​ 实际工作中,有时DataGrid控件某一列显示数据是从Enum集合里面选择出来的,那这时候设置列模版为ComboBox就能满足需求。而关于显示的实际内容,直接是Enum的string()返回值可能不太适合,这时候采用System.ComponentModel.Description是一个很好用的方法。

代码中定义的显示类型是Enum,实际结果在Description中声明。

定义 Enum Week

    [System.ComponentModel.Description("星期")]
public enum Week
{
[System.ComponentModel.Description("星期一")]
Monday, [System.ComponentModel.Description("星期二")]
Tuesday, [System.ComponentModel.Description("星期三")]
Wednesday, [System.ComponentModel.Description("星期四")]
Thursday, [System.ComponentModel.Description("星期五")]
Firday, [System.ComponentModel.Description("星期六")]
Saturday, [System.ComponentModel.Description("星期日")]
Sunday,
}

DataGrid模版:

<Grid.Resources>
<Style x:Key="DataGridTextColumnStyle" TargetType="{x:Type TextBlock}">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style> <Style TargetType="{x:Type DataGrid}">
<Setter Property="Margin" Value="0"/>
<Setter Property="Background" Value="#FF8CEB87"/>
<Setter Property="AutoGenerateColumns" Value="False"/>
<Setter Property="CanUserAddRows" Value="False"/>
<Setter Property="CanUserReorderColumns" Value="False"/>
<Setter Property="CanUserSortColumns" Value="False"/>
<Setter Property="CanUserResizeColumns" Value="False"/>
<Setter Property="CanUserResizeRows" Value="False"/>
<Setter Property="RowHeaderWidth" Value="30"/>
<Setter Property="RowHeight" Value="30"/>
<Setter Property="IsReadOnly" Value="True"/>
<Setter Property="CellStyle">
<Setter.Value>
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Setter.Value>
</Setter>
<Setter Property="ColumnHeaderStyle">
<Setter.Value>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources> <DataGrid ItemsSource="{Binding TestDatas}" LoadingRow="DataGrid_LoadingRow" Margin="0,0,403.6,10">
<DataGrid.Resources>
<ObjectDataProvider x:Key="Weeks" MethodName="GetNames" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:Week"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider> <local:WeekEnumToDescriptionConvertor x:Key="WeekEnumToDescription"/>
<local:WeekEnumToComboBoxIndexConvertor x:Key="WeekEnumToComboBoxIndex"/>
</DataGrid.Resources> <DataGrid.Columns>
<DataGridTemplateColumn Header="Week" Width ="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Source={StaticResource Weeks}, Converter={StaticResource WeekEnumToDescription}}"
SelectedIndex="{Binding TestWeek, Converter={StaticResource WeekEnumToComboBoxIndex}, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> <DataGridTextColumn Header="Message"
Binding="{Binding TestMsg}"
IsReadOnly="True"
ElementStyle ="{StaticResource DataGridTextColumnStyle}"
Width ="*"/>
</DataGrid.Columns>
</DataGrid>

WeekEnumToDescriptionConvertor、WeekEnumToComboBoxIndexConvertor实现代码:

    class WeekEnumToComboBoxIndexConvertor : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((int)(Week)value);
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((Week)(int)value);
}
} class WeekEnumToDescriptionConvertor : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var strValue = value as string[];
if (strValue != null)
{
var enValue = new Week[strValue.Length];
for (int i = 0; i < strValue.Length; i++)
{
if (Enum.TryParse(strValue[i], out enValue[i]))
strValue[i] = enValue[i].GetDescription();
}
}
return value;
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

EnumHelper代码:

    public static class EnumHelper
{
public static string GetDescription<T>(this T value) where T : struct
{
string result = value.ToString(); var fi = typeof(T).GetField(result); var attributes = (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(
typeof(System.ComponentModel.DescriptionAttribute), true); if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
return result;
} public static T GetValueByDescription<T>(this string description) where T : struct
{
Type type = typeof(T);
foreach (var field in type.GetFields())
{
if (field.Name == description)
{
return (T)field.GetValue(null);
} var attributes = (System.ComponentModel.DescriptionAttribute[])field.GetCustomAttributes(
typeof(System.ComponentModel.DescriptionAttribute), true); if (attributes != null && attributes.Length > 0)
{
if (attributes[0].Description == description)
{
return (T)field.GetValue(null);
}
}
}
throw new ArgumentException(string.Format($"{description} 未能找到对应的枚举"), "Description");
} public static T GetValue<T>(this string value) where T : struct
{
T result;
if (Enum.TryParse(value, true, out result))
{
return result;
}
throw new ArgumentException(string.Format($"{value} 未能找到对应的枚举"), "Value");
} }

最终效果图

完整代码

wpf 当DataGrid列模版是ComboBox时,显示信息的更多相关文章

  1. datagrid返回记录为0时显示“没有记录”

    datagrid返回记录为0时显示“没有记录”,此问题的 <script>var myview = $.extend({},$.fn.datagrid.defaults.view,{ on ...

  2. ArcGIS api for javascript——鼠标悬停时显示信息窗口

    描述 本例展示当用户在要素上悬停鼠标时如何显示InfoWindow.本例中,要素是查询USA州图层的QueryTask的查询结果.工作流程如下: 1.用户单击一个要素 2.要素是“加亮的”图形. 3. ...

  3. WPF 格式化输出- IValueConverter接口的使用 datagrid列中的值转换显示

    以前在用ASP.NET 做B/S系统时,可以方便地在GRIDVIEW DATAList等数据控件中,使用自定义的代码逻辑,比如 使用 <%# GetBalance(custID) %> 这 ...

  4. WPF 获取DataGrid 控件选中的单元格信息

    获取 DataGrid 选中的单元格的信息DataGridCellInfo cell_Info = this.studentTable.SelectedCells[0]; studentTableIt ...

  5. GridControl 无数据时显示信息

    图例: 主要代码如下: 说明:给GridView添加事件gv_CustomDrawEmptyForeground private void gv_CustomDrawEmptyForeground(o ...

  6. 编写 WPF DataGrid 列模板,实现更好的用户体验

    Julie Lerman 下载代码示例 最近我在为一个客户做一些 Windows Presentation Foundation (WPF) 方面的工作. 虽然我提倡使用第三方工具,但有时也会避免使用 ...

  7. WPF拖动DataGrid滚动条时内容混乱的解决方法

    WPF拖动DataGrid滚动条时内容混乱的解决方法 在WPF中,如果DataGrid里使用了模板列,当拖动滚动条时,往往会出现列表内容显示混乱的情况.解决方法就是在Binding的时候给Update ...

  8. WPF的DataGrid绑定ItemsSource后第一次加载数据有个别列移位的解决办法

    最近用WPF的DataGrid的时候,发现一个很弱智的问题,DataGrid的ItemsSource是绑定了一个属性: 然后取数给这个集合赋值的时候,第一次赋值,就会出现列移位 起初还以为是显卡的问题 ...

  9. WPF中DataGrid的ComboBox的简单绑定方式(绝对简单)

    在写次文前先不得不说下网上的其他wpf的DataGrid绑定ComboBox的方式,看了之后真是让人欲仙欲死. 首先告诉你一大堆的模型,一大堆的控件模板,其实或许你紧紧只想知道怎么让combobox怎 ...

随机推荐

  1. 各种数和各种反演(所谓FFT的前置知识?)

    每次问NC做多项式的题需要什么知识点. 各种数. 各种反演. 多项式全家桶. 然后我就一个一个地学知识点.然而还差好多,学到后面的前面的已经忘了(可能是我太菜吧不是谁都是NC啊) 然后发现每个知识点基 ...

  2. java之==操作符和equals操作符

    ==操作符: 基本数据类型比较值: 引用数据类型比较引用(是否指向同一个对象) equals操作符: 引用数据类型比较引用(是否指向同一个对象) 对于String.File.Date.包装类来说,只比 ...

  3. 用 Python 破解 WiFi 密码

    如今,WiFi 跟我们的生活息息相关,无处不在.没有 WiFi 的地方是没有灵魂的! ​ 然而,比没有WiFi更让人绝望的,是有满格WiFi信号却没有密码…… ​ 今天我们就来尝试下,如何利用pyth ...

  4. NIO中Buffer的重要属性关系解析

    Buffer 是java NIO中三个核心概念之一 缓存, 在java的实现体系中Buffer作为顶级抽象类存在 简单说,Buffer在做什么? 我们知道,在java IO中体系中, 因为InputS ...

  5. 【ZJOI 2014】力

    Problem Description 给出 \(n\) 个数 \(q_i\),给出 \(F_j\) 的定义如下: \[F_j=\sum_{i<j} \frac{q_iq_j}{(i-j)^2} ...

  6. PHPStorm 配置本地 WebServer 运行 PHP

    目标:PHPStorm 2018.2 通过配置运行 PHP 代码无需安装其它 Web Server File -> Settings菜单找到PHP,设置 CLI Interpreter PHP的 ...

  7. Python中Collections模块的Counter容器类使用教程

    1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict.set.list.tuple以外的一些特殊的容器类型,分别是: OrderedDict类 ...

  8. Python的小数据存储,用什么格式更有逼格?

    小数据存储 我们在编写代码的时候,经常会涉及到数据存储的情况,如果是爬虫得到的大数据,我们会选择使用数据库,或者excel存储.但如果只是一些小数据,或者说关联性较强且存在存储后复用的数据,我们该如何 ...

  9. vue-cli 3.0按需引入element-ui

    vue-cli 3.0脚手架初始化项目成功后,如果需要按需引入element-ui,按照官网的教程,会报如下错误: 这个是由于babel编译插件版本问题,需要安装最新的babel编译插件“@babel ...

  10. C#(1)运用C#实现一键从Word文档转换TXT文本的功能

    有想直接从Word转TXT文本的可以看看,懒得复制粘贴的也可以使用下,方便而快捷!! 首先打开vs2012创建一个简单的form窗体: 里面主要的就是一个存放Word文档的button和一个执行的bu ...