WPF中的DependencyProperty怎么用 WPF依赖属性创建与使用

admin 百科 10
WPF 中的 DependencyProperty 是实现数据绑定、样式、模板、动画等功能的基础,需通过静态注册、GetValue/SetValue 访问,并推荐提供同名包装属性;其创建分三步:定义 static readonly 字段、调用 Register 注册、添加包装属性;XAML 中可直接使用如 ;支持元数据(默认值、变更/强制回调)及 FrameworkPropertyMetadata 标记;仅限 DependencyObject 派生类使用,禁在构造函数中 SetValue 初始化。

WPF中的DependencyProperty怎么用 WPF依赖属性创建与使用-第1张图片-佛山资讯网

WPF 中的 DependencyProperty 是实现数据绑定、样式、模板、动画、属性继承等核心功能的基础。它不是普通 .NET 属性,而是一种由 WPF 属性系统管理的特殊属性,必须通过静态注册方式声明,并配合 GetValue / SetValue 方法访问。

依赖属性怎么创建

创建依赖属性需三步:定义静态只读字段、在类中注册、提供标准包装属性(可选但强烈推荐)。

  • 使用 DependencyProperty.Register 注册,传入属性名、类型、所属类类型、可选元数据(如默认值、回调)
  • 注册返回的 DependencyProperty 对象必须赋给 public static readonly 字段
  • 为方便 XAML 和 C# 代码调用,建议提供同名的 .NET 属性包装器,内部调用 GetValue/SetValue

示例(在自定义控件 MyButton 中定义 CornerRadius 依赖属性):

public class MyButton : Control
{
    // 1. 静态只读字段
    public static readonly DependencyProperty CornerRadiusProperty =
        DependencyProperty.Register(
            nameof(CornerRadius),
            typeof(double),
            typeof(MyButton),
            new PropertyMetadata(0.0)); // 默认值为 0.0
<pre class="brush:php;toolbar:false;">// 2. 包装属性(非必需但实用)
public double CornerRadius
{
    get => (double)GetValue(CornerRadiusProperty);
    set => SetValue(CornerRadiusProperty, value);
}

登录后复制

}

依赖属性怎么在 XAML 中使用

XAML 中使用依赖属性和普通属性写法一致,只要该属性是公开的包装属性或直接支持属性语法即可。

  • 直接赋值:<mybutton cornerradius="8"></mybutton>
  • 绑定表达式:<mybutton cornerradius="{Binding Radius}"></mybutton>
  • 动画目标:<doubleanimation to="12" storyboard.targetproperty="CornerRadius"></doubleanimation>
  • 样式 Setter:<setter property="CornerRadius" value="6"></setter>

注意:XAML 实际解析时,会通过反射找到 CornerRadiusProperty 字段并调用 SetValue,所以包装属性名必须与字段名(去掉 Property 后缀)严格匹配。

标签: c# .net 重绘

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~