wpf 当DataGrid列模版是ComboBox时,显示信息
实际工作中,有时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时,显示信息的更多相关文章
- datagrid返回记录为0时显示“没有记录”
datagrid返回记录为0时显示“没有记录”,此问题的 <script>var myview = $.extend({},$.fn.datagrid.defaults.view,{ on ...
- ArcGIS api for javascript——鼠标悬停时显示信息窗口
描述 本例展示当用户在要素上悬停鼠标时如何显示InfoWindow.本例中,要素是查询USA州图层的QueryTask的查询结果.工作流程如下: 1.用户单击一个要素 2.要素是“加亮的”图形. 3. ...
- WPF 格式化输出- IValueConverter接口的使用 datagrid列中的值转换显示
以前在用ASP.NET 做B/S系统时,可以方便地在GRIDVIEW DATAList等数据控件中,使用自定义的代码逻辑,比如 使用 <%# GetBalance(custID) %> 这 ...
- WPF 获取DataGrid 控件选中的单元格信息
获取 DataGrid 选中的单元格的信息DataGridCellInfo cell_Info = this.studentTable.SelectedCells[0]; studentTableIt ...
- GridControl 无数据时显示信息
图例: 主要代码如下: 说明:给GridView添加事件gv_CustomDrawEmptyForeground private void gv_CustomDrawEmptyForeground(o ...
- 编写 WPF DataGrid 列模板,实现更好的用户体验
Julie Lerman 下载代码示例 最近我在为一个客户做一些 Windows Presentation Foundation (WPF) 方面的工作. 虽然我提倡使用第三方工具,但有时也会避免使用 ...
- WPF拖动DataGrid滚动条时内容混乱的解决方法
WPF拖动DataGrid滚动条时内容混乱的解决方法 在WPF中,如果DataGrid里使用了模板列,当拖动滚动条时,往往会出现列表内容显示混乱的情况.解决方法就是在Binding的时候给Update ...
- WPF的DataGrid绑定ItemsSource后第一次加载数据有个别列移位的解决办法
最近用WPF的DataGrid的时候,发现一个很弱智的问题,DataGrid的ItemsSource是绑定了一个属性: 然后取数给这个集合赋值的时候,第一次赋值,就会出现列移位 起初还以为是显卡的问题 ...
- WPF中DataGrid的ComboBox的简单绑定方式(绝对简单)
在写次文前先不得不说下网上的其他wpf的DataGrid绑定ComboBox的方式,看了之后真是让人欲仙欲死. 首先告诉你一大堆的模型,一大堆的控件模板,其实或许你紧紧只想知道怎么让combobox怎 ...
随机推荐
- vue_04day 路由初始
目录 vue_04 项目初始: vue 文件构造: vue项目目录结构: 项目入口(main.js): vue项目启动生命周期: 根组件(vue.js): router.js: 创建的页面: 全局样式 ...
- java之对象创建时各成员变量的初始值
除了byte short int long float double char bollean这基础类型外,其余的都是引用类型 成员变量类型 初始值 byte 0 short 0 int 0 long ...
- LeetCode 第70题动态规划算法
导言 看了 动态规划(https://www.cnblogs.com/fivestudy/p/11855853.html)的帖子,觉得写的很好,记录下来. 动态规划问题一直是算法面试当中的重点和难点, ...
- 【ST开发板评测】Nucleo-F411RE开箱报告
前言 面包板又举办开发板试用活动了,很荣幸能获得一块ST官方的Nucleo-F411RE开发板,感谢面包板社区和ST意法半导体的赞助,这是我第一次试用官方的开发板,收到板子后查了一些关于ST官方开发板 ...
- javascript截取字符串的最后几个字符
在JavaScript中截取字符串一般是使用内置的substring()方法和substr()方法,这两个方法功能都很强大,也都能实现截取字符串中的最后几个字符. substring()方法 Java ...
- Asp .Net Core Excel导入和导出
ASP .Net Core使用EPPlus实现Api导入导出,这里使用是EPPlus 4.5.2.1版本,.Net Core 2.2.在linux上运行的时候需要安装libgdiplus . 下面我们 ...
- 通过修改VAD属性破除锁页机制
Windows内核分析索引目录:https://www.cnblogs.com/onetrainee/p/11675224.html 技术学习来源:火哥(QQ:471194425) 注释:因为自己的知 ...
- 数据显示按规格向datatable中增加空白记录
/// <summary> /// 按前台分页样式为datatable增加空行 /// </summary> /// <param name="gridPage ...
- Assign a Custom Image 设置自定义图标
In this lesson, you will learn how to associate a business class with a custom image. This image wil ...
- vscode自动修复eslint规范的插件及配置
在开发大型项目中,经常都是需要多人合作的.相信大家一定都非常头疼于修改别人的代码的吧,而合理的使用eslint规范可以让我们在代码review时变得轻松,也可以让我们在修改小伙伴们的代码的时候会更加清 ...