Avalonia Data Templates 介绍 Avalonia UI 中 DataTemplate(数据模板)的用法:用模板描述一个数据对象如何渲染成 UI,并说明模板可应用于 ItemsControl 及其子类(ListBox、TreeView,通过 ItemTemplate)、TableViewColumn.CellTemplate(12.1+)与 DataGrid 模板列、ContentControl 及其子类(通过 ContentTemplate),以及任何 Content 属性——Avalonia 会沿模板树向上查找匹配的 DataTemplate。模板按数据对象的运行时类型匹配,作用域内第一个匹配的模板生效。
主要能力与使用方式:
-
内联 DataTemplate:在 ListBox.ItemTemplate 中直接写 DataTemplate,并用 x:DataType 启用模板内的编译绑定。资料指出 12.0+ 编译绑定是默认行为,每个 {Binding} 都需要已知的 x:DataType,否则构建失败(AVLN2000);真正动态的数据可用 {ReflectionBinding Path}。11.x 中编译绑定为可选项。
-
ContentControl 与 DataTemplate:通过 ContentControl.ContentTemplate 为内容指定模板;多页面导航时,App 级模板比逐 ContentControl 模板更实用。
-
App 级模板(全局自动选择):在 App.axaml 的 Application.DataTemplates 中注册模板后,这些模板在整个应用生效,ViewModel 类型作为 Content 或列表项出现时会自动匹配。示例中 ContentControl 只绑定 Content 即可自动渲染正确视图。
-
模板作用域解析顺序:显式 ContentTemplate/ItemTemplate(最高优先级)→ 控件自身的 Control.DataTemplates → 沿逻辑树向上查找父控件的 DataTemplates → Application.DataTemplates(全局兜底)。第一个匹配生效;集合内顺序有意义,更具体的类型应放在基类型之前。
-
模板类型选择器(IDataTemplate):实现 IDataTemplate,依据运行时类型或属性值有条件地选择模板。示例中 AnimalTemplateSelector 提供 DogTemplate、CatTemplate,Build 按类型分派,Match 判断是否为 Dog 或 Cat,再在 Window.Resources 中定义并通过 StaticResource 赋给 ItemTemplate。
-
FuncDataTemplate(纯代码):适用于代码后置、自定义控件或不便使用 XAML 的场景。可创建简单模板,也可在模板内建立绑定;12.0+ 使用 CompiledBinding.Create,11.x 惯用法或反射回退可用 new Binding(...),12 中可用 new ReflectionBinding(...)。
-
列模板(TableView 12.1+、DataGrid):TableViewColumn.CellTemplate 优先于 Binding;DataGrid(Avalonia.Controls.DataGrid,仅维护)使用 DataGridTemplateColumn.CellTemplate,方式相同。12 中列绑定是编译的,行类型尽可能从 ItemsSource 推断,否则需显式指定 DataType 或回退到 ReflectionBinding。
-
可复用模板资源:在 Window.Resources 中用 x:Key 定义一次 DataTemplate,再在 ListBox.ItemTemplate、ContentControl.ContentTemplate 中通过 StaticResource 引用。
-
TreeDataTemplate(层级/TreeView):TreeDataTemplate 在 DataTemplate 基础上增加用于子节点的 ItemsSource 绑定,示例中 TreeNode 含 Name、Icon、Children(ObservableCollection)。树中混合类型(文件与文件夹)可用 IDataTemplate 选择器按具体类型构建。
-
ItemsControl 面板自定义:通过 ItemsControl.ItemsPanel 与 ItemsPanelTemplate 更换布局面板,示例包括 WrapPanel(横向换行)和 UniformGrid(Columns=3)。
-
设计时数据:在模板相关控件中使用 Design.DataContext 指定设计时 ViewModel。
常见错误(资料列出):DataTemplate 缺少 x:DataType(12.0+ 编译绑定默认或 11.x 启用编译绑定时构建失败 AVLN2000,需 x:DataType 或 ReflectionBinding);12.0+ 在 C# 模板中使用 new Binding(...)(应改用 CompiledBinding.Create 或 ReflectionBinding);12.0+ 使用 {Binding ^Stream} 等绑定插件(插件已移除);资源作用域错误(Window.Resources 中的模板对嵌套 UserControl 内的模板不可见,共享模板应放在 Application.Resources 或 Application.DataTemplates);对树数据误用 DataTemplate 而非 TreeDataTemplate(无法为子节点提供 ItemsSource 绑定,TreeView 不会递归);按接口类型匹配(自动选择按具体运行时类型,IDataTemplate.Match() 需显式检查具体类型);同一作用域同类型多个模板(第一个总是生效,应去重或用键控资源表示多种展示);循环模板引用(模板创建的 ContentControl 又绑定回同类型 ViewModel 导致无限递归,应用键控模板或包装 ViewModel 打破循环);同时设置 ItemTemplate 又依赖自动选择(显式 ItemTemplate 总是优先,应移除 ItemTemplate 以使用全局自动选择)。