CellStyleSelector
This article shows how to style RadGridView's cells conditionally by applying CellStyleSelector.
To download a runnable project with the example from this article, visit our SDK repository. You can find the example in the GridView/CellStyleSelector folder.
The
CellStyle
property of the column has a higher priority thanCellStyleSelector
. This means, if theCellStyle
is set, theCellStyleSelector
won't be invoked.
Assume we have RadGridView bound to a collection of sports clubs. Each club has a StadiumCapacity property. What we want to achieve is to set the background color of the StadiumCapacity cells to Red if the capacity > 50 000 or Yellow if the capacity < 50 000:
Figure 1: The expected result
Follow these steps to configure CellStyleSelector:
Create a new class that inherits the StyleSelector class.
-
Override its default SelectStyle method. Return the style that will be applied to the framework element (GridViewCell in our case).
In this example, we declare two styles that will be applied depending on the underlying data:
BigStadiumStyle
SmallStadiumStyle
Example 1: The StadiumCapacityStyle class
- In the XAML file, define the style selector as a resource and set the properties of BigStadiumStyle and SmallStadiumStyle:
Example 2: Set the different styles for the style selector
The "my:" prefix before StadiumCapacityStyle specifies the mapping for the namespace of the project: xmlns:my=".
If you use our Implicit Themes, base the conditional style on the style that is defined for the corresponding theme:
Example 3: Set the style when using implicit styles
The GridViewCellStyle resource is accessible when you use the NoXaml dlls and you merged the associated .xaml files. The Style is defined in the Telerik.Windows.Controls.GridView.xaml file which is why you can access it using the
StaticResource
keyword.
- Finally, set the CellStyleSelector property of the data column that represents the StadiumCapacity field:
Example 4: Set CellStyleSelector for the column
Since the virtualization of the GridView is turned on by default, it is not recommended to work with the visual elements (i.e. GridViewCell) and their properties. You should not set properties of GridViewCell inside SelectStyle method. Read more on UI Virtualization.