WPF中的DataTemplate
在 WPF 中,数据模板(DataTemplate)同样用于定义“数据如何在 UI 上显示”。以下是一个典型的 WPF 数据模板示例,包含定义、使用及核心特性说明。
场景说明
假设有一个 Student
类(数据模型),包含 Name
(姓名)、Age
(年龄)、Grade
(年级)属性,我们希望在 UI 上以“卡片式”展示该数据,而不是默认的类名文本。
完整示例代码
<Window x:Class="WpfDataTemplateDemo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfDataTemplateDemo"Title="WPF 数据模板示例" Height="300" Width="400"><!-- 1. 定义数据模板:WPF 中数据模板通常放在 Resources 资源集合中 --><Window.Resources><!-- 为 Student 类型定义模板:DataType 指定数据类型(无需 x:Key,自动匹配) --><DataTemplate DataType="{x:Type local:Student}"><!-- 模板内容:自定义 Student 数据的 UI 结构 --><Border Background="LightGray" BorderBrush="Gray" BorderThickness="1" CornerRadius="5" Padding="10" Margin="5"><StackPanel><TextBlock Text="学生信息" FontWeight="Bold" FontSize="14"/><TextBlock Text="{Binding Name}" Margin="0,5,0,0"/> <!-- 绑定 Name 属性 --><TextBlock Text="{Binding Age, StringFormat='年龄:{0}'}"/> <!-- 格式化显示 --><TextBlock Text="{Binding Grade, StringFormat='年级:{0}'}"/></StackPanel></Border></DataTemplate></Window.Resources><!-- 2. 使用数据模板:通过 ContentControl 或列表控件展示数据 --><Grid><!-- 单个数据展示:Content 绑定 Student 对象,WPF 会自动匹配上面的模板 --><ContentControl Content="{Binding CurrentStudent}"/><!-- 列表数据展示:ListBox 的 ItemsSource 绑定 Student 集合,每个项自动应用模板 --><!-- <ListBox ItemsSource="{Binding StudentList}"/> --></Grid>
</Window>
后台数据模型(C#)
// Student 数据类
namespace WpfDataTemplateDemo
{public class Student{public string Name { get; set; }public int Age { get; set; }public string Grade { get; set; }}// 窗口后台数据上下文public partial class MainWindow : Window{public Student CurrentStudent { get; set; }public MainWindow(){InitializeComponent();// 初始化数据CurrentStudent = new Student { Name = "张三", Age = 15, Grade = "高一(3)班" };DataContext = this; // 绑定数据上下文}}
}
运行效果
UI 会显示一个浅灰色卡片,包含“学生信息”标题,以及绑定的“张三”“年龄:15”“年级:高一(3)班”文本,而不是默认的 WpfDataTemplateDemo.Student
类名。
WPF 数据模板的核心特点(通过示例体现)
- 存储位置:通常放在
Resources
集合中(如<Window.Resources>
),而 Avalonia 放在DataTemplates
中。 - 自动匹配:通过
DataType="{x:Type local:Student}"
指定模板对应的类型,无需x:Key
,WPF 会自动为该类型的数据应用模板。 - 适用场景:
- 单个数据:通过
ContentControl.Content
绑定对象,自动应用模板。 - 列表数据:通过
ListBox.ItemsSource
绑定集合,每个子项自动应用模板。
- 单个数据:通过
- 匹配限制:WPF 模板默认只精确匹配具体类,不支持接口或派生类(例如,
Student
的派生类GoodStudent
不会自动匹配Student
模板,而 Avalonia 支持)。
这个例子展示了 WPF 数据模板的核心用法:通过 Resources
定义模板,关联数据类型,让框架自动将数据转换为指定的 UI 样式,实现数据与 UI 的解耦。