本文记录 wpf 在 dotnet 9 的一项 xaml 编写语法改进点,此改进点用于解决编写 style 的 setter 进行给 value 赋值时,不能将 value 当成默认内容,需要多写 value 标签的问题。通过此改进点可减少两行 xaml 代码
在原先的 wpf 版本里面,对 style 的 setter 填充复杂的对象内容时,大概的示例代码如下
<style targettype="button"> <setter property="template"> <setter.value> <controltemplate targettype="button"> ... </controltemplate> </setter.value> </setter> </style>
可以看到 <setter.value>
属于不可省略的内容
在本次引入的改进之后,即可将 setter 的 value 当成默认内容,从而减少 <setter.value>
的代码,改进后的写法如下
<style targettype="button"> <setter property="template"> <controltemplate targettype="button"> ... </controltemplate> </setter> </style>
此改进是在许多年前,由 thomas levesque 大佬在 https://github.com/dotnet/wpf/issues/84 提出的。被微软的 anjali 在 https://github.com/dotnet/wpf/pull/8534 实现
此变更将影响 xaml 语法,对应的文档也进行了同步更新,详细请看 https://github.com/dotnet/dotnet-api-docs/pull/9581
为什么之前的版本里面,必须编写 <setter.value>
呢?这是因为在原先的版本里面 style 的 setter 的 value 不是默认的内容,即在 setter 标签里面直接放入内容,将不能被放入到 value 属性里面
在 https://github.com/dotnet/wpf/pull/8534 的实现里面,将 setter 的 value 当成默认内容,于是在 setter 里面放入的内容,将会自动给 value 进行赋值
上述的核心逻辑在 src/microsoft.dotnet.wpf/src/presentationframework/system/windows/markup/baml2006/wpfgeneratedknowntypes.cs 里面,给创建 setter 时,配置 baml 类型里面内容对应的属性名是 "value" 属性名,如以下代码
private wpfknowntype create_bamltype_setter(bool isbamltype, bool usev3rules) { var bamltype = new wpfknowntype(this, // schemacontext 556, "setter", typeof(system.windows.setter), isbamltype, usev3rules); bamltype.defaultconstructor = delegate() { return new system.windows.setter(); }; bamltype.contentpropertyname = "value"; // 这是本次更改的核心逻辑 bamltype.freeze(); return bamltype; }
当前的 wpf 在 https://github.com/dotnet/wpf 完全开源,使用友好的 mit 协议,意味着允许任何人任何组织和企业任意处置,包括使用,复制,修改,合并,发表,分发,再授权,或者销售。在仓库里面包含了完全的构建逻辑,只需要本地的网络足够好(因为需要下载一堆构建工具),即可进行本地构建
发表评论