WPF FlexGrid Style Skills Part 3: Setting the Selected Cell Color and Font
_Translation of a post by Alice Yue. Original post in Chinese located here._ In the first two article of this series, WPF FlexGrid Style Skills Part 1 and WPF FlexGrid Style Skills Part 2, we covered setting the selected cell background and foreground colors as well as font style. In addition to using the ApplyCellStyles method, we can use the CreateCellContent method to implement the cell settings for color and style effects. This article discusses how to set the style of the selected cell using these methods.
Using CreateCellContent
CreateCellContent method allows us to change the style of a cell. For instance we can use the method to rotate text:
public override void CreateCellContent (C1FlexGrid grid, Border bdr, CellRange rng)
{
base.CreateCellContent (grid, bdr, rng);
var tb = bdr.Child as TextBlock;
if (tb! = Null && rng.Column == 2)
{
ContentPresenter cp = (VisualTreeHelper.GetParent (tb) as ContentPresenter)
System.Windows.Media.RotateTransform rotateTransform = new RotateTransform ();
rotateTransform.Angle = 50;
tb.LayoutTransform = rotateTransform;
}
}
This has the following visual effect: With this knowledge, we can set the style as we see fit.
Styling a selected cell
Both selected foreground color and background color of a cell can be set directly through the SelectionBackground and SelectionForeground properties. Other font styles can still be implemented your own custom CellFactory and using the methods CreateCellContent or ApplyCellStyle. Either method can be used, and below is the code for using CreateCellContent:
public override void CreateCellContent (C1FlexGrid grid, Border bdr, CellRange rng)
{
base.CreateCellContent (grid, bdr, rng);
var columnindex = rng.Column;
var rowindex = rng.Row;
var tb = bdr.Child as TextBlock;
bool selected = (columnindex == grid.Selection.Column && rowindex == grid.Selection.Row);
if (tb! = null && selected)
{
ContentPresenter cp = (VisualTreeHelper.GetParent (tb) as ContentPresenter)
System.Windows.Media.RotateTransform rotateTransform = new RotateTransform ();
rotateTransform.Angle = 50;
tb.LayoutTransform = rotateTransform;
tb.FontWeight = FontWeights.Bold;
tb.FontSize = 14;
}
}
Note that the selectionChanged event is called to refresh:
void flex_SelectionChanged ( object sender, CellRangeEventArgs e)
{
flex.Invalidate ();
}
This gives you the following result when run: [
Download the sample for this article.
](//cdn.mescius.io/assets/developer/blogs/legacy/c1/2017/05/Wpf_Flex_CellstyleOnSelected_1.zip)