讲师中心 微信公众号
AI工具推荐 视频效率加速

[UWP]为附加属性和依赖属性自定义代码段(兼容UWP和WPF)

千婷同学_1460

千婷同学_1460

发布时间:2025-09-03 09:06:20

|

904人浏览过

|

来源于php中文网

原创

  1. 前言

我之前介绍过依赖属性和附加属性的代码段,这两个代码段我已经使用了很多年,帮了我不少忙。不过,我已经多年没有对它们进行过修改,resharper总是提示我可以优化生成的代码。这次,我决定采纳它的建议,并顺便简单介绍一下如何自定义代码段。

  1. VisualStudio自带代码段的问题

以依赖属性为例,一个完整的依赖属性应该包含以下部分:

  • 注册依赖属性并生成依赖属性标识符。依赖属性标识符为一个
    public static readonly DependencyProperty
    字段。依赖属性标识符的名称必须为“属性名+Property”。
  • 在
    PropertyMetadata
    中指定属性默认值。
  • 实现属性包装器。为属性提供
    get
    和
    set
    访问器,在
    Getter
    和
    Setter
    中分别调用
    GetValue
    和
    SetValue
    。
    Getter
    和
    Setter
    中不应该有其它任何自定义代码。
  • 如果需要监视属性值变更,可以在
    PropertyMetadata
    中定义一个
    PropertyChangedCallback
    方法。因为这个方法是静态的,可以再实现一个同名的实例方法(可以参考
    ContentControl
    的
    OnContentChanged
    方法)。

更详尽的规范可以参考《Framework Design Guidelines》。

public int MyProperty{    
    get { return (int)GetValue(MyPropertyProperty); }    
    set { SetValue(MyPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =    
    DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));

如上所示,VisualStudio自带的依赖属性的代码段

propdp
只实现了最基本的功能,
PropertyChangedCallback
等函数还需要自己实现,这部分也相当麻烦。另外,
ownerclass
基本都是当前类的名字,没有理由不使用当前类的名字作为默认值。

/// <summary>
/// 获取或设置MyProperty的值
/// </summary>  
public int MyProperty{    
    get => (int)GetValue(MyPropertyProperty);    
    set => SetValue(MyPropertyProperty, value);
}
/// <summary>
/// 标识 MyProperty 依赖属性。
/// </summary>
public static readonly DependencyProperty MyPropertyProperty =    
    DependencyProperty.Register(nameof(MyProperty), typeof(int), typeof(MainPage), new PropertyMetadata(default(int), OnMyPropertyChanged));
private static void OnMyPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args){    
    var oldValue = (int)args.OldValue;    
    var newValue = (int)args.NewValue;    
    if (oldValue == newValue)        
        return;    
    var target = obj as MainPage;    
    target?.OnMyPropertyChanged(oldValue, newValue);
}
/// <summary>
/// MyProperty 属性更改时调用此方法。
/// </summary>
/// MyProperty 属性的旧值。
/// MyProperty 属性的新值。
protected virtual void OnMyPropertyChanged(int oldValue, int newValue){}

上面是我自定义的代码段,改进了这些地方:

  • Getter
    和
    Setter
    使用了表达式主体;
  • DependencyProperty.Register
    的第一个参数使用了
    nameof()
    关键字代替了字符串;
  • typeof(MainPage)
    这里使用了代码段函数
    ClassName()
    直接获取当前类的名称;
  • 依赖属性的默认值使用了
    default()
    关键字,因为绝大部分情况下依赖属性的默认值就是数据类型的默认值,修改默认值的工作交给
    DefaultStyle
    的
    Setter
    ;
  • 添加了相对完整的
    PropertyChangedCallback
    函数。
  1. 如何自定义代码段

基本上,一个代码段就是一个XML文件,

3.1 代码段的结构

<?xml version="1.0" encoding="utf-8"?>
<codesnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <codesnippet format="1.0.0">
        <keywords>
            <keyword>dp</keyword>
        </keywords>
        <snippettypes>
            <snippettype>SurroundsWith</snippettype>
        </snippettypes>
        <title>Dependency Property</title>
        <author>dino.c</author>
        <description>For Dependency Property</description>
        <helpurl></helpurl>
        <shortcut>dp</shortcut>
        <snippet>
            <references>
                <reference>
                    <assembly></assembly>
                </reference>
            </references>
            <declarations>
                <literal editable="true">
                    <id>PropertyType</id>
                    <tooltip>属性类型</tooltip>
                    <default>int</default>
                    <function></function>
                </literal>
                ...
            </declarations>
        </snippet>
    </codesnippet>
</codesnippets>

如上所示,代码段定义XML中主要分成以下几个部分:

  • Header:包括Keyword、Shortcut等信息。Author和Description等可有可无;
  • Declarations:代码段中的变量;
  • Code:代码段的代码。

3.2 代码段中的变量

在我定义的依赖属性代码段中包含了三个变量:

<literal editable="true">
    <id>PropertyType</id>
    <tooltip>属性类型</tooltip>
    <default>int</default>
    <function></function>
</literal>
<literal editable="true">
    <id>MyProperty</id>
    <tooltip>属性名</tooltip>
    <default>MyProperty</default>
    <function></function>
</literal>
<literal editable="false">
    <id>classname</id>
    <tooltip>类名</tooltip>
    <function>ClassName()</function>
    <default>ClassNamePlaceholder</default>
</literal>

其中

classname
不可编辑,它使用了
ClassName()
这个代码段函数,返回包含已插入代码段的类的名称。其它可用的代码段函数可以参考这个页面:代码段函数。

引用变量的语法是

$变量名$
,如下所示:

Gitguard Skill
Gitguard Skill

Git 安全扫描与仓库健康审计 — 基于熵的密钥检测、复合健康评分、提交质量分析、陈旧分支清理以及依赖扫描

下载
public static readonly DependencyProperty $MyProperty$Property =    
    DependencyProperty.Register(nameof($MyProperty$), typeof($PropertyType$), typeof($classname$), new PropertyMetadata(default($PropertyType$), On$MyProperty$Changed));

3.3 导入代码段

在菜单上选择“工具->代码片段管理器”:

[UWP]为附加属性和依赖属性自定义代码段(兼容UWP和WPF)

在“代码片段管理器”窗口中点击“导入”,选中需要导入的文件后打开“导入代码片段”,选择位置后点击“完成”即可完成代码段导入:

[UWP]为附加属性和依赖属性自定义代码段(兼容UWP和WPF)

3.4 最终成果

依赖属性的代码段:

<?xml version="1.0" encoding="utf-8"?>
<codesnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <codesnippet format="1.0.0">
        <keywords>
            <keyword>dp</keyword>
        </keywords>
        <snippettypes>
            <snippettype>SurroundsWith</snippettype>
        </snippettypes>
        <title>Dependency Property</title>
        <author>dino.c</author>
        <description>For Dependency Property</description>
        <helpurl></helpurl>
        <shortcut>dp</shortcut>
        <snippet>
            <references>
                <reference>
                    <assembly></assembly>
                </reference>
            </references>
            <declarations>
                <literal editable="true">
                    <id>PropertyType</id>
                    <tooltip>属性类型</tooltip>
                    <default>int</default>
                    <function></function>
                </literal>
                <literal editable="true">
                    <id>MyProperty</id>
                    <tooltip>属性名</tooltip>
                    <default>MyProperty</default>
                    <function></function>
                </literal>
                <literal editable="false">
                    <id>classname</id>
                    <tooltip>类名</tooltip>
                    <function>ClassName()</function>
                    <default>ClassNamePlaceholder</default>
                </literal>
            </declarations>
            <![CDATA[
            /// <summary>
            /// 获取或设置$MyProperty$的值
            /// </summary>
            public $PropertyType$ $MyProperty$
            {
                get => ($PropertyType$)GetValue($MyProperty$Property);
                set => SetValue($MyProperty$Property, value);
            }
            /// <summary>
            /// 标识 $MyProperty$ 依赖属性。
            /// </summary>
            public static readonly DependencyProperty $MyProperty$Property =
                DependencyProperty.Register(nameof($MyProperty$), typeof($PropertyType$), typeof($classname$), new PropertyMetadata(default($PropertyType$), On$MyProperty$Changed));
            private static void On$MyProperty$Changed(DependencyObject obj,DependencyPropertyChangedEventArgs args)
            {
                var oldValue = ($PropertyType$)args.OldValue;
                var newValue = ($PropertyType$)args.NewValue;
                if (oldValue == newValue)
                    return;

                var target= obj as $classname$;
                target?.On$MyProperty$Changed(oldValue, newValue);
            }
            /// <summary>
            /// $MyProperty$ 属性更改时调用此方法。
            /// </summary>
            /// $MyProperty$ 属性的旧值。
            /// $MyProperty$ 属性的新值。
            protected virtual void On$MyProperty$Changed($PropertyType$ oldValue,$PropertyType$ newValue)
            {
            }
            ]]>
        </snippet>
    </codesnippet>
</codesnippets>

附加属性的代码段:

<?xml version="1.0" encoding="utf-8"?>
<codesnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <codesnippet format="1.0.0">
        <keywords>
            <keyword>ap</keyword>
        </keywords>
        <snippettypes>
            <snippettype>Expansion</snippettype>
        </snippettypes>
        <title>Attached Property</title>
        <author>dino.c</author>
        <description>For Attached Property</description>
        <helpurl></helpurl>
        <shortcut>ap</shortcut>
        <snippet>
            <references>
                <reference>
                    <assembly></assembly>
                </reference>
            </references>
            <declarations>
                <literal editable="true">
                    <id>PropertyType</id>
                    <tooltip>属性类型</tooltip>
                    <default>int</default>
                    <function></function>
                </literal>
                <literal editable="true">
                    <id>MyProperty</id>
                    <tooltip>属性名</tooltip>
                    <default>MyProperty</default>
                    <function></function>
                </literal>
                <literal editable="false">
                    <id>classname</id>
                    <tooltip>类名</tooltip>
                    <function>ClassName()</function>
                    <default>ClassNamePlaceholder</default>
                </literal>
            </declarations>
            <![CDATA[
            /// <summary>
            /// 从指定元素获取 $MyProperty$ 依赖项属性的值。
            /// </summary>
            /// <param name="obj">从中读取属性值的元素。</param>
            /// <returns>从属性存储获取的属性值。</returns>
            public static $PropertyType$ Get$MyProperty$(DependencyObject obj) => ($PropertyType$)obj.GetValue($MyProperty$Property);
            /// <summary>
            /// 将 $MyProperty$ 依赖项属性的值设置为指定元素。
            /// </summary>
            /// <param name="obj">对其设置属性值的元素。</param>
            /// <param name="value">要设置的值。</param>
            public static void Set$MyProperty$(DependencyObject obj, $PropertyType$ value) => obj.SetValue($MyProperty$Property, value);
            /// <summary>
            /// 标识 $MyProperty$ 依赖项属性。
            /// </summary>
            public static readonly DependencyProperty $MyProperty$Property =
                DependencyProperty.RegisterAttached("$MyProperty$", typeof($PropertyType$), typeof($classname$), new PropertyMetadata(default($PropertyType$), On$MyProperty$Changed));
            private static void On$MyProperty$Changed(DependencyObject obj, DependencyPropertyChangedEventArgs args)
            {
                var oldValue = ($PropertyType$)args.OldValue;
                var newValue = ($PropertyType$)args.NewValue;
                if (oldValue == newValue)
                    return;

                var target = obj as $classname$;
            }
            ]]>
        </snippet>
    </codesnippet>
</codesnippets>
  1. 结语

虽然这两个代码段比较复杂,并不是每次创建依赖属性都需要这么完整,但删除代码总比增加代码简单得多,所以我多年来每次创建依赖属性和附加属性都是使用这两个代码段。

WPF的依赖属性可以十分复杂,但平时用不到这么多功能,所以和UWP使用相同的代码段就足够了。

完整的代码段已上传到Github。

  1. 参考代码段

热门AI工具

更多
讯飞智作

讯飞智作是一款AI视频创作工具,AI文本配音工具,数字人课程、营销视频制作。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

小橡皮AI

一款AI工具,主要用于小橡皮一键去AI味,将机器味重的内容改得更有活人感,防止因为 AI 内容被平台打上 AI 标签,以及限流,适合需要提升相关任务效率的用户。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

Seko
Seko Hot

一款AI视频创作工具,主要用于商汤科技推出的创编一体的AI短视频创作Agent,适合需要提升相关任务效率的用户。

UP简历
UP简历 Hot

一款AI办公效率工具,主要用于基于AI技术的免费在线简历制作工具,适合需要提升相关任务效率的用户。

SkildArt
SkildArt Hot

SkildArt是一款AI文本写作工具,一站式 AI 视觉创作平台。

PixPix
PixPix Hot

PixPix是一款面向电商视觉生产的AI商品图生成工具。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

相关专题

更多
数据类型有哪几种
数据类型有哪几种

数据类型有整型、浮点型、字符型、字符串型、布尔型、数组、结构体和枚举等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

3371

2023.10.31

php数据类型
php数据类型

本专题整合了php数据类型相关内容,阅读专题下面的文章了解更多详细内容。

574

2025.10.31

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

582

2026.02.12

pdf怎么转换成xml格式
pdf怎么转换成xml格式

将 pdf 转换为 xml 的方法:1. 使用在线转换器;2. 使用桌面软件(如 adobe acrobat、itext);3. 使用命令行工具(如 pdftoxml)。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

4984

2024.04.01

xml怎么变成word
xml怎么变成word

步骤:1. 导入 xml 文件;2. 选择 xml 结构;3. 映射 xml 元素到 word 元素;4. 生成 word 文档。提示:确保 xml 文件结构良好,并预览 word 文档以验证转换是否成功。想了解更多xml的相关内容,可以阅读本专题下面的文章。

6477

2024.08.01

xml是什么格式的文件
xml是什么格式的文件

xml是一种纯文本格式的文件。xml指的是可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。想了解更多相关的内容,可阅读本专题下面的相关文章。

2602

2024.11.28

mysql标识符无效错误怎么解决
mysql标识符无效错误怎么解决

mysql标识符无效错误的解决办法:1、检查标识符是否被其他表或数据库使用;2、检查标识符是否包含特殊字符;3、使用引号包裹标识符;4、使用反引号包裹标识符;5、检查MySQL的配置文件等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

17100

2023.12.04

Python标识符有哪些
Python标识符有哪些

Python标识符有变量标识符、函数标识符、类标识符、模块标识符、下划线开头的标识符、双下划线开头、双下划线结尾的标识符、整型标识符、浮点型标识符等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

1223

2024.02.23

DBeaver怎么导入数据
DBeaver怎么导入数据

DBeaver数据导入专题,整理Excel、CSV、SQL、TXT等常见文件的数据导入方法,涵盖目标数据库选择、数据表创建、字段映射、数据类型设置及导入参数配置等操作,帮助用户将本地文件中的数据写入数据库,并了解批量导入、重复数据处理和导入失败等常见问题的解决方法。

20

2026.11.05

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Python uv官方安装与入门文档
Python uv官方安装与入门文档

共0课时 | 0人学习

Buffalo框架快速入门指南
Buffalo框架快速入门指南

共0课时 | 0人学习

Conan 2 安装指南
Conan 2 安装指南

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn