信息发布→ 登录 注册 退出

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

发布时间:2025-09-03

点击量:
  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
基本都是当前类的名字,没有理由不使用当前类的名字作为默认值。

/// 
/// 获取或设置MyProperty的值
///   
public int MyProperty{    
    get => (int)GetValue(MyPropertyProperty);    
    set => SetValue(MyPropertyProperty, value);
}
/// 
/// 标识 MyProperty 依赖属性。
/// 
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);
}
/// 
/// MyProperty 属性更改时调用此方法。
/// 
/// 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 代码段的结构



    
        
            dp
        
        
            SurroundsWith
        
        Dependency Property
        dino.c
        For Dependency Property
        
        dp
        
            
                
                    
                
            
            
                
                    PropertyType
                    属性类型
                    int
                    
                
                ...
            
        
    

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

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

3.2 代码段中的变量

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


    PropertyType
    属性类型
    int
    


    MyProperty
    属性名
    MyProperty
    


    classname
    类名
    ClassName()
    ClassNamePlaceholder

其中

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

引用变量的语法是

$变量名$
,如下所示:

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

3.3 导入代码段

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

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

3.4 最终成果

依赖属性的代码段:



    
        
            dp
        
        
            SurroundsWith
        
        Dependency Property
        dino.c
        For Dependency Property
        
        dp
        
            
                
                    
                
            
            
                
                    PropertyType
                    属性类型
                    int
                    
                
                
                    MyProperty
                    属性名
                    MyProperty
                    
                
                
                    classname
                    类名
                    ClassName()
                    ClassNamePlaceholder
                
            
            
            /// 获取或设置$MyProperty$的值
            /// 
            public $PropertyType$ $MyProperty$
            {
                get => ($PropertyType$)GetValue($MyProperty$Property);
                set => SetValue($MyProperty$Property, value);
            }
            /// 
            /// 标识 $MyProperty$ 依赖属性。
            /// 
            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);
            }
            /// 
            /// $MyProperty$ 属性更改时调用此方法。
            /// 
            /// $MyProperty$ 属性的旧值。
            /// $MyProperty$ 属性的新值。
            protected virtual void On$MyProperty$Changed($PropertyType$ oldValue,$PropertyType$ newValue)
            {
            }
            ]]>
        
    

附加属性的代码段:



    
        
            ap
        
        
            Expansion
        
        Attached Property
        dino.c
        For Attached Property
        
        ap
        
            
                
                    
                
            
            
                
                    PropertyType
                    属性类型
                    int
                    
                
                
                    MyProperty
                    属性名
                    MyProperty
                    
                
                
                    classname
                    类名
                    ClassName()
                    ClassNamePlaceholder
                
            
            
            /// 从指定元素获取 $MyProperty$ 依赖项属性的值。
            /// 
            /// 从中读取属性值的元素。
            /// 从属性存储获取的属性值。
            public static $PropertyType$ Get$MyProperty$(DependencyObject obj) => ($PropertyType$)obj.GetValue($MyProperty$Property);
            /// 
            /// 将 $MyProperty$ 依赖项属性的值设置为指定元素。
            /// 
            /// 对其设置属性值的元素。
            /// 要设置的值。
            public static void Set$MyProperty$(DependencyObject obj, $PropertyType$ value) => obj.SetValue($MyProperty$Property, value);
            /// 
            /// 标识 $MyProperty$ 依赖项属性。
            /// 
            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$;
            }
            ]]>
        
    
  1. 结语

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

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

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

  1. 参考代码段
标签:# default  # 几个  # 我已经  # 自带  # 管理器  # 所示  # 都是  # 自定义  # 这两个  # 使用了  # 默认值  # wpf  # visualstudio  # github  # typeof  # windows  # 访问器  # Property  # public  # 字符串  # register  # 标识符  # xml  # 数据类型  # Static  # ai  # 工具  # git  # word  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!