Use the CellDecorationStyleSelector Property
This example demonstrates how to use CellDecorationStyleSelector property to set custom background to the grid cells depending on a property from the model.
To style the text in the grid cells, you have to use the CellContentStyleSelector property.
Example
First lets create a simple class that represents our data:
Example 1: Create Data Models
public enum Gender
{
Male,
Female
}
public class Person
{
public string Name { get; set; }
public Gender Gender { get; set; }
}
And a ViewModel class that will be used as DataContext of the grid.
Example 2: Create ViewModel
public class ViewModel
{
public ObservableCollection<Person> Data { get; set; }
public ViewModel()
{
Data = new ObservableCollection<Person>()
{
new Person() { Name = "Anna", Gender = Gender.Female },
new Person() { Name = "Tom", Gender = Gender.Male },
new Person() { Name = "Jack", Gender = Gender.Male },
new Person() { Name = "Emmy", Gender = Gender.Female }
};
}
}
Example 3: Create Custom StyleSelector
public class CellStyleSelector : StyleSelector
{
public Style MaleStyle { get; set; }
public Style FemaleStyle { get; set; }
protected override Style SelectStyleCore(object item, DependencyObject container)
{
var cell = (item as DataGridCellInfo);
var person = cell.Item as Person;
if (person.Gender == Gender.Female)
{
return this.FemaleStyle;
}
return this.MaleStyle;
}
}
We have to set the Style properties with
TargetType="Rectangle"
.
Example 4: Create Custom Styles
<local:CellStyleSelector x:Key="BackgroundSelector">
<local:CellStyleSelector.MaleStyle>
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="RoyalBlue"/>
</Style>
</local:CellStyleSelector.MaleStyle>
<local:CellStyleSelector.FemaleStyle>
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="HotPink"/>
</Style>
</local:CellStyleSelector.FemaleStyle>
</local:CellStyleSelector>
Example 5: Set the CellDecorationStyleSelector property
<telerikGrid:RadDataGrid ItemsSource="{Binding Data}" AutoGenerateColumns="False" Width="300" Height="300">
<telerikGrid:RadDataGrid.DataContext>
<local:ViewModel/>
</telerikGrid:RadDataGrid.DataContext>
<telerikGrid:RadDataGrid.Columns>
<telerikGrid:DataGridTextColumn PropertyName="Name" CellDecorationStyleSelector="{StaticResource BackgroundSelector}" />
<telerikGrid:DataGridTextColumn PropertyName="Gender" CellDecorationStyleSelector="{StaticResource BackgroundSelector}" />
</telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>