C1 WPF C1FlexGrid设置样式技巧:单元格前景色和字体设置

来源:互联网 发布:js删除div内容 编辑:程序博客网 时间:2024/06/05 08:17

<ComponentOne Studio for WPF下载>

在之前我们讨论过给单元格设置背景色:通过重写ApplyCellStyles方法,然后设置Border的Background属性实现。本文就在此基础上讨论如何对单元格字体进行设置。

还是通过ApplyCellStyles方法,我们可以拿到Border,然后从Border.Child拿到TextBlock,就可以通过TextBlock的Font相关属性(Foreground,FontWeight, TextDecorations等)设置字体。

前景色

因此设置单元格的前景色和背景色的代码参考如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
publicoverride void ApplyCellStyles(C1FlexGrid grid, CellType cellType, CellRange range, Border bdr)
{
var columnindex = range.Column;
var rowindex = range.Row;
var _textblock = bdr.Child asTextBlock;
if(_textblock == nullreturn;
//check if the cell is selected or not
boolselected=(columnindex == grid.Selection.Column && rowindex == grid.Selection.Row);
if((columnindex == 2) && (rowindex == 3)&&!selected)
{
//set the customizations on the cell when it is not selected
bdr.Background = newSolidColorBrush(Colors.Red);
_textblock.Foreground= Brushes.Yellow;
}
 
}

代码效果如下:

字体样式设置

再此基础上,我们来讨论字体的设置,只需设置属性即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
publicoverride void ApplyCellStyles(C1FlexGrid grid, CellType cellType, CellRange range, Border bdr)
{
var columnindex = range.Column;
var rowindex = range.Row;
var _textblock = bdr.Child asTextBlock;
if(_textblock == nullreturn;
//check if the cell is selected or not
boolselected=(columnindex == grid.Selection.Column && rowindex == grid.Selection.Row);
if((columnindex == 2) && (rowindex == 3)&&!selected)
{
//set the customizations on the cell when it is not selected
bdr.Background = newSolidColorBrush(Colors.Red);
_textblock.Foreground= Brushes.Yellow;
_textblock.FontSize = 14d;
_textblock.FontWeight = FontWeights.Bold;
_textblock.FontStyle = FontStyles.Italic;
 
}
 
}

这个时候,该单元格的背景色,前景色和字体样式都发生了改变。非选择的时候:

选择的时候:

改进代码:改变选择单元格的样式

如果这个时候希望这个特定的单元格,在选择的时候字体样式发生改变(恢复成未设置的状态),这个时候我们就需要添加代码,在选择的时候设置_textblock的Font相关属性重置。代码参考:

1
2
3
4
5
6
if(selected)
{
_textblock.FontSize = 12d;
_textblock.FontWeight = FontWeights.Normal;
_textblock.FontStyle = FontStyles.Normal;
}

注意:需要在方法的最后进行Invalidate操作。

代码如下:

1
grid.Invalidate(newCellRange(3, 2));

这个时候选择单元格的结果如图:

本文的示例请下载:Wpf_Flex_CellstyleOnCell_update.zip

PS: 关于ComponentOne,这些产品你可以关注>>
本文转载自葡萄城
0 0