​ 实际工作中,有时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. 第420期 Python 周刊

    文章.教程或讲座 Python 数据科学教程:分析 Stack Overflow 2019 年开发者调查表** https://www.youtube.com/watch?v=_P7X8tMplsw ...

  2. Linux中长时间运行程序的方法

    一.场景: 如果临时有一个命令需要长时间运行,比如 python hello.py ,什么方法能最简便的保证它在后台稳定运行呢?解决方法:      当用户注销(logout)或者网络断开时,终端会收 ...

  3. IE浏览器远程代码执行高危漏洞(CVE-2019-1367)

    IE浏览器远程代码执行高危漏洞(CVE-2019-1367)加固遇到的问题 一.背景介绍 Internet Explorer,是微软公司推出的一款网页浏览器.用户量极大.9月23日微软紧急发布安全更新 ...

  4. .net core使用HttpClient发送代理请求_程序内抓包_Fiddler抓包

    前言:  通过Fiddler抓取浏览器请求数据,相信大家已经都会用了,我们知道Fiddler是通过在本机计算器添加一个默认的代理服务器来实现的抓包数据的,端口号为:8888. 其实当我们打开Fiddl ...

  5. C# Xamarin 数据绑定入门基础

    目录 关于数据绑定 视图-视图绑定 绑定模式 简单的集合绑定 C# Xamarin 数据绑定入门基础 关于数据绑定 Xamarin 单向.双向绑定 Xaml绑定 C#代码绑定 在此之前,几段 伪代码 ...

  6. Format a Property Value 设置属性值的格式

    In this lesson, you will learn how to set a display format and an edit mask to a business class prop ...

  7. 十八道JVM面试题总汇(附解析)

    一.Java 类加载过程? Java 类加载需要经历以下7 个过程: 1. 加载 加载是类加载的第一个过程,在这个阶段,将完成以下三件事情: • 通过一个类的全限定名获取该类的二进制流. • 将该二进 ...

  8. Android项目实战(五十八):Android 保存图片文件到本地,相册/图库查看不到的处理

    将一个图片文件写入到本地目录,然后去相册查看,会查找不到这个图片文件,但是去文件目录下查找,确确实实有该图片文件. 问题在于相册是一个独立的app,它并不会去刷新本地图片,所以需要在写图片文件成功之后 ...

  9. iTerm2 使用代理

    0x00 事件 因为 brew 安装极慢,所以需要 iTerm2 设置代理解决速度问题. 0x01 解决 代理软件开启本地 Http 端口: iTerm 设置代理: $ vim ~/.zshrc # ...

  10. Linux-3.14.12内存管理笔记【建立内核页表(3)

    前面已经分析了内核页表的准备工作以及内核低端内存页表的建立,接着回到init_mem_mapping()中,低端内存页表建立后紧随着还有一个函数early_ioremap_page_table_ran ...