条件格式是Excel一个非常常见的功能,所谓动态条件格式,也就是根据数据库的内容,动态的为每个单元格设置格式样式而已。本文主要讨论如何在WPF的网格应用程序中开发实现这一功能。ComponentOne Studio for WPF中的网格控件C1FlexGrid有一个叫CellFactory的类,CellFactory类允许在单元格中自定义网格,接下来就主要用到这个类来实现动态条件格式的效果。
首先,创建一个继承于CellFactory类的类。
public class CustomCellFactory : CellFactory
{
}
然后用CellFactory类来覆盖CreateCellContent()方法,用条件来设置单元式的边框元素的背景。
public override void CreateCellContent(C1FlexGrid grid, Border bdr, CellRange rng)
{
base.CreateCellContent(grid, bdr, rng);
//format cells in second column
if (rng.Column == 2)
{
if (grid[rng.Row, rng.Column].ToString() == "Japan")
{
bdr.Background = new SolidColorBrush(Colors.LimeGreen);
}
else if (grid[rng.Row, rng.Column].ToString() == "India")
{
bdr.Background = new SolidColorBrush(Colors.MediumVioletRed);
}
else if (grid[rng.Row, rng.Column].ToString() == "United States")
{
bdr.Background = new SolidColorBrush(Colors.Yellow);
}
else if (grid[rng.Row, rng.Column].ToString() == "United Kingdom")
{
bdr.Background = new SolidColorBrush(Colors.Gold);
}
}
}
然后动态条件格式就完成了,下面这个GIF就是其动态效果: