Suppose we have a DataGrid that displays data about student score information and for each different score we will need to display the corresponding rating column. In this case we need to create many different templates for the review and display it with the corresponding condition.

Here is the student class that I created as an example:

public class Student
{
public Student(string code,string name,double totalScore)
{
Code = code;Name = name;TotalScore = totalScore;
}
public string Code { get; set; }
public string Name { get; set; }
public double TotalScore { get; set; }
}

First, we create a class to handle the selection of the display template:

public class StudentTemplateSelector: DataTemplateSelector
{
public DataTemplate BadTemplate

{ get; set; }
public DataTemplate MediumTemplate

{ get; set; }
public DataTemplate GoodTemplate

{ get; set; }
public DataTemplate ExcellentTemplate
{
get;set;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)

{

Student student = item as Student;
if (student != null)

{

if (student.TotalScore >= 9)

return ExcellentTemplate;

else if (student.TotalScore >= 8)

return GoodTemplate;
else if (student.TotalScore >= 5)
return MediumTemplate;
else return BadTemplate;
}

else

return base.SelectTemplate(item, container);

}
}

Next is to create the corresponding template on xaml

<Window.Resources>

<DataTemplate x:Key=”ExcellentTemplate”>

<TextBlock Margin=”2″ Text=”Excellent” Foreground=”Red”/>

</DataTemplate>

<DataTemplate x:Key=”GoodTemplate”>

<TextBlock Margin=”2″ Text=”Good” Foreground=”Yellow”/>

</DataTemplate>
<DataTemplate x:Key=”MediumTemplate”>

<TextBlock Margin=”2″ Text=”Medium” Foreground=”Green”/>

</DataTemplate>
<DataTemplate x:Key=”BadTemplate”>

<TextBlock Margin=”2″ Text=”Bad” Foreground=”Gray”/>

</DataTemplate>

</Window.Resources>

Finally display it on the DataGrid

<DataGrid ItemsSource=”{Binding}”

AutoGenerateColumns=”False”>

<DataGrid.Columns>

<DataGridTextColumn Header=”Student Code” Binding=”{Binding Code}”/>

<DataGridTextColumn Header=”Name” Binding=”{Binding Name}”/>

<DataGridTextColumn Header=”Total Score” Binding=”{Binding TotalScore}”/>

<DataGridTemplateColumn Header=”Grade”>

<DataGridTemplateColumn.CellTemplateSelector>

<local:StudentTemplateSelector

BadTemplate=”{StaticResource BadTemplate}” MediumTemplate=”{StaticResource MediumTemplate}” ExcellentTemplate=”{StaticResource ExcellentTemplate}”

GoodTemplate=”{StaticResource GoodTemplate}”/>

</DataGridTemplateColumn.CellTemplateSelector>

</DataGridTemplateColumn>

</DataGrid.Columns>

</DataGrid>

Please run it and see the results.