--- description: XAML 视图编写约定(头部模板、数据绑定、输入限长、BindingProxy、DRY、颜色、布局注释、枚举绑定等),编辑 .xaml 文件时生效 alwaysApply: false globs: "**/*.xaml" --- # XAML 视图编写约定 项目 XAML 默认不添加 `AutomationProperties.Name`。 ## View XAML 头部模板 ```XML ``` ## Dialog View XAML ```XML ``` - `{core:DISource Type=local:XxxViewModel}` 绑定 ViewModel - `d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"` 提供设计时数据 - `UserControlStyle` 与 `ViewModelBaseEx` 强相关,必须搭配使用 ### 控件必须有设计数据 页面、弹窗和 `DataTemplate` 应能在 XAML 设计器中直接看出字段内容、排列方向、对齐和间距。设计值使用 `d:` 命名空间,根元素声明 `xmlns:d`、`xmlns:mc` 和 `mc:Ignorable="d"`,保留运行时绑定。 - `TextBox`、`TextBlock` 的文本来自绑定或默认为空时,必须设置有业务含义的非空示例,如 `d:Text="示例商贸有限公司"`。静态文案已可见时无需重复填写。 - 绑定集合的 `ItemsControl`、`ListBox`、`ComboBox`、`DataGridEx` 等必须提供设计时数据,默认使用 `d:ItemsSource="{d:SampleData ItemCount=5}"`。行数可按实际布局调整。下拉框要预览选中项时可加 `d:SelectedIndex="0"`。 - 其他控件按实际显示属性提供设计值,例如绑定标题的 `wpf:TitleContent` 用 `d:Title="中转仓快递费(元/单)"`,金额输入框用 `d:Value="2.20"`,绑定按钮文案用 `d:Content="保存"`。运行时按状态显示的区域,可用 `d:Visibility="Visible"` 预览。 - 集合模板既要能看到多行,也要能看清每行内容。若样本数据未填充自定义控件的显示属性,在模板内补相应的 `d:` 值。 ## BindingProxy + CommandProxy(DataTemplate/ContextMenu 绑定) **在 `DataTemplate`、`ContextMenu`、`DataGridTemplateColumn.CellTemplate` 中禁止使用 `RelativeSource AncestorType`,必须用 `BindingProxy` + `CommandProxy`。** ### UserControl.Resources 注册 ```xml ``` **`BindingProxy` 映射关系**:`Data="{Binding}"` 把 ViewModel 存到 `BindingProxy.Data`。引用时 `Path=Data.SelectedItem` 中 `Data` 对应 `BindingProxy.Data`(即 ViewModel)。 ### 文字只读显示 尽量使用 `TextBlock` 而不是 `Label` ### DataTemplate(CellTemplate)中 Command 用 CommandProxy,行数据用 `{Binding}`: ```xml