WPF DataGrid显格式
Guide to WPF DataGrid formatting using bindings
Introduction
Formatting WPF DataGrid content depending on business logic data is way too difficult. Especially since MSDN is not telling you anything about it. I have spent weeks to figure out how to get the binding right. Let me show you how it is done to save you time and endless searches on the Internet.
WPF DataGrid Structure
The container hierarchy of a DataGrid looks like this:
DataGrid
DataGridRows
DataGridCell
TextBlock
A DataGrid contains DataGridRows which contain DataGridCells which contain exactly one TextBlock, if it is a TextColumn and in read mode (editing mode uses a TextBox). Of course, the visual tree is a bit more complicated:
Note that DataGridColumn is not part of the visual tree. Whatever is defined in DataGridColumn will be applied to all cells of that column.
WPF Binding Basics
The binding gets assigned to a FrameworkElement property, which constitutes the target of the binding.
WPF needs two source information to make a binding work:
- Source: Which object provides the information
- Path: Which property of the source should be used
Usually, the Source gets inherited from the DataContext of a parent container, often the Window itself. But DataGrid's DataContext cannot be used for the binding of rows and cells, because each row needs to bind to a different business logic object.
DataGridColumn specifies the binding for the value to be displayed in the cell with the DataGridColumn.Binding property. The DataGrid creates during runtime a binding for every TextBlock.Text. Unfortunately, the DataGrid does not support binding for any other property of TextBlock. If you try to setup a style for the TextBlock yourself, the binding will most likely fail, because it wouldn't know which business object from the ItemsSource to use.
Business data used
The business data example is based on some stock taking figures. A stock item looks like this:
public class StockItem {
public string Name { get; set; }
public int Quantity { get; set; }
public bool IsObsolete { get; set; }
}
The sample data:
| Name | Quantity | IsObsolete |
| Many items | 100 | false |
| Enough items | 10 | false |
| Shortage item | 1 | false |
| Item with error | -1 | false |
| Obsolete item | 200 | true |
Connecting a DataGrid with business data
Even connecting a DataGrid with the business data is not trivial. Basically, a CollectionViewSource is used to connect the DataGrid with the business data:
The CollectionViewSource does the actual data navigation, sorting, filtering, etc.
- Define a
CollectionViewSourceinWindows.Resource
<Window.Resources>
<CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>
- The gotcha here is that you
must
- set the
CollectionViewType
- . If you don't, the GridView will use
BindingListCollectionView
- , which does not support sorting. Of course, MSDN does not explain this anywhere.
- Set the
DataContextof the DataGrid to theCollectionViewSource.
<DataGrid
DataContext="{StaticResource ItemCollectionViewSource}"
ItemsSource="{Binding}"
AutoGenerateColumns="False"
CanUserAddRows="False">
- In the code behind, find the
CollectionViewSourceand assign your business data to the Source property
//create business data
var itemList = new List<stockitem>();
itemList.Add(new StockItem {Name= "Many items", Quantity=100, IsObsolete=false});
itemList.Add(new StockItem {Name= "Enough items", Quantity=10, IsObsolete=false});
... //link business data to CollectionViewSource
CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;</stockitem>
In this article, data gets only read. If the user should be able to edit the data, use an ObservableCollection.
DataGrid Formatting
Formatting a column

Formatting a whole column is easy. Just set the property, like Fontweight directly in the DataGridColumn:
<DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" FontWeight="Bold"/>
The binding here is not involved with the formatting, but specifies the content of the cell (i.e., Text property of TextBlock).
Formatting complete rows

Formatting the rows is special, because there will be many rows. The DataGrid offers for this purpose the RowStyle property. This style will be applied to every DataGridRow.
<datagrid.rowstyle>
<style targettype="DataGridRow">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self},
Path=Item.Quantity, Converter={StaticResource QuantityToBackgroundConverter}}"/>
</style>
</datagrid.rowstyle>
The DatGridRow has an Item property, which contains the business logic object for that row. The binding for the DataRow must therefore bind to itself ! The path is a bit surprising, because Item is of type Object and doesn't know any business data properties. But the WPF binding applies a bit of magic and finds the Quantity property of StockItem anyway.
In this example, the background of a row depends on the value of the Quantity property of the business object. If there are many items in stock, the background should be white, if only few are left, the background should be grey. The QuantityToBackgroundConverter performs the necessary calculation:
class QuantityToBackgroundConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is int) {
int quantity = (int)value;
if (quantity>=100) return Brushes.White;
if (quantity>=10) return Brushes.WhiteSmoke;
if (quantity>=0) return Brushes.LightGray;
return Brushes.White; //quantity should not be below 0
}
//value is not an integer. Do not throw an exception
// in the converter, but return something that is obviously wrong
return Brushes.Yellow;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
Formatting a cell based on the displayed value
Formatting just a cell instead of the whole row is a challenge. In a text column, the cell has a TextBlock which needs to be styled. To create a Style for TextBlocks is easy, but how can the TextBlock property be bound to the proper business object ? The DataGrid is binding already the Text property of the TextBlock. If the styling depends only on the cell value, we can simply use a self binding to this Text property.
Example: In our stock grid, the Quantity should always be greater than or equal zero. If a quantity is negative, it is an error and should be displayed in red:
<Setter Property="Foreground"
Value="{Binding
RelativeSource={RelativeSource Self},
Path=Text,
Converter={StaticResource QuantityToForegroundConverter}}" />
Formatting a cell based on business logic data
The most complex case is if the cell format does not depend on the cell value, but some other business data. In our example, the quantity of an item should be displayed as strike through if it is obsolete. To achieve this, the TextDecorations property needs to be linked to the business object of that row. Meaning the TextBlock has to find the parent DataGridRow. Luckily, binding to a parent visual object can be done with a relative source:
<Setter Property="TextDecorations"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}},
Path =Item.IsObsolete,
Converter={StaticResource IsObsoleteToTextDecorationsConverter}}" />
public class IsObsoleteToTextDecorationsConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is bool) {
if ((bool)value) {
TextDecorationCollection redStrikthroughTextDecoration =
TextDecorations.Strikethrough.CloneCurrentValue();
redStrikthroughTextDecoration[0].Pen = new Pen {Brush=Brushes.Red, Thickness = 3 };
return redStrikthroughTextDecoration;
}
}
return new TextDecorationCollection();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
Code
See the Zip file for the complete source code of the sample.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Share
WPF DataGrid显格式的更多相关文章
- WPF DataGrid常用属性记录
WPF DataGrid常用属性记录 组件常用方法: BeginEdit:使DataGrid进入编辑状态. CancelEdit:取消DataGrid的编辑状态. CollapseRowGroup:闭 ...
- WPF DATAGRID - COMMITTING CHANGES CELL-BY-CELL
In my recent codeproject article on the DataGrid I described a number of techniques for handling the ...
- WPF DataGrid某列使用多绑定后该列排序失效,列上加入 SortMemberPath 设置即可.
WPF DataGrid某列使用多绑定后该列排序失效 2011-07-14 10:59hdongq | 浏览 1031 次 悬赏:20 在wpf的datagrid中某一列使用了多绑定,但是该列排序失 ...
- xceed wpf datagrid
<!--*********************************************************************************** Extended ...
- 获取wpf datagrid当前被编辑单元格的内容
原文 获取wpf datagrid当前被编辑单元格的内容 确认修改单元个的值, 使用到datagrid的两个事件 开始编辑事件 BeginningEdit="dataGrid_Beginni ...
- WPF DataGrid绑定一个组合列
WPF DataGrid绑定一个组合列 前台: <Page.Resources> <local:InfoConverter x:Key="converter& ...
- WPF DataGrid自定义样式
微软的WPF DataGrid中有很多的属性和样式,你可以调整,以寻找合适的(如果你是一名设计师).下面,找到我的小抄造型的网格.它不是100%全面,但它可以让你走得很远,有一些非常有用的技巧和陷阱. ...
- WPF DataGrid Custommization using Style and Template
WPF DataGrid Custommization using Style and Template 代码下载:http://download.csdn.net/detail/wujicai/81 ...
- 编写 WPF DataGrid 列模板,实现更好的用户体验
Julie Lerman 下载代码示例 最近我在为一个客户做一些 Windows Presentation Foundation (WPF) 方面的工作. 虽然我提倡使用第三方工具,但有时也会避免使用 ...
随机推荐
- 自制IPsec_vpn综合实验
实验需求 R1.R2间tunnel建立私网: Vpn网关间配置ipsec实现数据加密: 使用tunnel模式下的ESP包头封装: 使用3des加密算法,md5摘要算法: 设置NAT旁路绕行流量: 利用 ...
- mybaties-plus入门
目前正在维护的公司的一个项目是一个ssm架构的java项目,dao层的接口有大量数据库查询的方法,一个条件变化就要对应一个方法,再加上一些通用的curd方法,对应一张表的dao层方法有时候多达近20个 ...
- 201521123084 《Java程序设计》第6周学习总结
1. 本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图,对面向对象思想进行一个总结. 注1:关键词与内容不求多,但概念之间的联系要清晰,内容覆盖 ...
- 201521123081《Java程序设计》 第4周学习总结
1. 本周学习总结 1.1 尝试使用思维导图总结有关继承的知识点. 参考资料:百度脑图(上图为第3周实验学习总结中未展开部分) 1.2 使用常规方法总结其他上课内容. 多态.思维导图中有提及. 2. ...
- 201521123004 《Java程序设计》第12周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容. 2. 书面作业 将Student对象(属性:int id, String name,int age,doubl ...
- Java:final、static关键字 详解+两者结合使用
一 final关键字 1) 关于final的重要知识点 final关键字可以用于成员变量.本地变量.方法以及类. final成员变量必须在声明的时候初始化或者在构造器中初始化,否则就会报编译错误. ...
- yum仓库管理
yum在线管理 rpm包的管理分为 rpm命令管理和yum在线管理,rpm命令管理由于可能需要解决各种依赖问题,在安装软件的时候可能显得比较麻烦,然而,yum在线管理正好和它相反.Yum(全称为 Ye ...
- 《Head First 设计模式》读书笔记(1) - 策略模式
<Head First 设计模式>(点击查看详情) 1.写在前面的话 之前在列书单的时候,看网友对于设计模式的推荐里说,设计模式的书类别都大同小异,于是自己就选择了Head First系列 ...
- Oracle存储过程 一个具体实例
表结构信息,并不是用oracle描述的,但是后面的存储过程是针对oracle的 ----------------个人交易流水表----------------------------------- c ...
- OSGi-入门篇之模块层(02)
1 什么是模块化 模块层是OSGi框架中最基础的一部分,其中Java的模块化特性在这一层得到了很好的实现.但是这种实现与Java本身现有的一些模块化特性又有明显的不同. 在OSGi中模块的定义可以参考 ...



