C1 WPF C1FlexGrid設定樣式技巧:單元格前景色和字型設定
阿新 • • 發佈:2019-02-15
在之前我們討論過給單元格設定背景色:通過重寫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 |
public
override
void
ApplyCellStyles(C1FlexGrid grid, CellType cellType, CellRange range, Border bdr)
{
var
columnindex = range.Column;
var
rowindex = range.Row;
var
_textblock = bdr.Child as
TextBlock;
if
(_textblock == null ) return ;
//check
if the cell is selected or not
bool
selected=(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
= new
SolidColorBrush(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 |
public
override
void
ApplyCellStyles(C1FlexGrid grid, CellType cellType, CellRange range, Border bdr)
{
var
columnindex = range.Column;
var
rowindex = range.Row;
var
_textblock = bdr.Child as
TextBlock;
if
(_textblock == null ) return ;
//check
if the cell is selected or not
bool
selected=(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
= new
SolidColorBrush(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( new
CellRange(3, 2));
|
這個時候選擇單元格的結果如圖: