以DataGrid中单元格模板选择器为例进行说明。第一列显示姓名,第二列根据身高选择不同的数据模板,身高低于160时,单元格显示红色背景;不低于160时,显示绿色。效果如图:
1、构造后台数据
public class Student
{
private string _name;
private UInt16 _height;
public String Name
{
get => _name;
set => _name = value;
}
public UInt16 Height
{
get => _height;
set => _height = value;
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<Student> _students = new();
public MainWindow()
{
InitializeComponent();
Students.Add(new Student() { Name = "小宏", Height = 162 });
Students.Add(new Student() { Name = "小强", Height = 161 });
Students.Add(new Student() { Name = "小红", Height = 158 });
Students.Add(new Student() { Name = "小云", Height = 164 });
this.StudentDataGrid.ItemsSource = Students;
}
public ObservableCollection<Student> Students
{
get => _students;
}
}
2、编写前台代码
<Window.Resources>
<DataTemplate x:Key="Qualified">
<TextBlock Text="{Binding Height}" Background="Green"></TextBlock>
</DataTemplate>
<DataTemplate x:Key="Unqualified">
<TextBlock Text="{Binding Height}" Background="Red"></TextBlock>
</DataTemplate>
</Window.Resources>
<DataGrid x:Name="StudentDataGrid" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="姓名" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTemplateColumn Header="身高">
<DataGridTemplateColumn.CellTemplateSelector>
<local:HeightSelector QualifiedTemplate="{StaticResource Qualified}" UnqualifiedTemplate="{StaticResource Unqualified}"></local:HeightSelector>
</DataGridTemplateColumn.CellTemplateSelector>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
3、创建选择器
public class HeightSelector : DataTemplateSelector
{
public DataTemplate QualifiedTemplate { get; set; }
public DataTemplate UnqualifiedTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
Student stu = item as Student;
if (stu != null)
{
if (stu.Height >= 160)
{
return QualifiedTemplate;
}
else
{
return UnqualifiedTemplate;
}
}
return base.SelectTemplate(item, container);
}
}