WPF依赖属性和附加属性

在WPF(Windows Presentation Foundation)中,依赖属性和附加属性是两种非常有用的特性,它们扩展了传统属性的功能,提供了更强大的数据绑定、样式和模板定制能力。

一:依赖属性(Dependency Properties)

依赖属性是WPF中的一种特殊类型的属性,它们基于DependencyProperty类。与传统的CLR(公共语言运行时)属性不同,依赖属性没有存储值的后备字段;相反,它们的值存储在DependencyObject的PropertyStore中。这使得依赖属性能够支持许多高级功能,如数据绑定、样式、动画和继承。

  • 声明依赖属性
    在WPF中,你通常使用DependencyProperty.Register或DependencyProperty.RegisterReadOnly方法来注册一个依赖属性。例如:
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register(  
    "MyProperty", typeof(string), typeof(MyClass), new PropertyMetadata("DefaultValue"));  
  
public string MyProperty  
{  
    get { return (string)GetValue(MyPropertyProperty); }  
    set { SetValue(MyPropertyProperty, value); }  
}

在这个例子中,MyProperty是一个依赖属性,它有一个类型为string的值,并在MyClass类中注册。
注意:如果你注册的属性名是“MyProperty”,那么MyProperty +Property 格式就是你的DependencyProperty类型,这是必须的规则!

  • 实战使用:
    我们给自定义button添加一个依赖属性,并在使用时通过ControlTemplate进行重组时进行依赖属性绑定
    定义部分:
    public class JSCButton : Button
    {
        // 注册依赖属性
        public static readonly DependencyProperty ImageSourceExProperty =
            DependencyProperty.Register("ImageSourceEx", typeof(ImageSource), typeof(JSCButton), new PropertyMetadata(null));

        // CLR包装器属性  
        public ImageSource ImageSourceEx
        {
            get { return (ImageSource)GetValue(ImageSourceExProperty); }
            set { SetValue(ImageSourceExProperty, value); }
        }
    }

ButtonStyle1部分:

<Style x:Key="ButtonStyle1" TargetType="{x:Type local:JSCButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:JSCButton}">
                <Border>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="1*"/>
                            <RowDefinition Height="3*"/>
                            <RowDefinition Height="1*"/>
                        </Grid.RowDefinitions>
                        <Border Grid.Row="1" Background="Red" Width="86" Height="87">
                            <Image Width="50" Height="50" Source="{TemplateBinding ImageSourceEx}"/>
                        </Border>
                        <TextBlock Grid.Row="2" Text="{TemplateBinding Content}" FontSize="18" TextAlignment="Center"/>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

使用部分:

<local:JSCButton ImageSourceEx="/Resources/CompileResources/Images/next.png" Grid.Column="0" Content="音量+" Grid.Row="0" Style="{StaticResource ButtonStyle1}"/>
<local:JSCButton ImageSourceEx="/Resources/CompileResources/Images/next.png" Grid.Column="1" Content="当前分贝" Grid.Row="0" Style="{StaticResource ButtonStyle1}"/>
<local:JSCButton ImageSourceEx="/Resources/CompileResources/Images/next.png" Grid.Column="2" Content="音量-" Grid.Row="0" Style="{StaticResource ButtonStyle1}"/>

呈现效果:

image.png

这样我们既使用控件模板自定义了button,使其增加了image图片展示部分,又可以给不同的button使用不同的图片赋值展示。
如果不使用依赖属性,可以看到如下报错
企业微信截图_17344140443282.png

企业微信截图_173441403311.png

从下面的代码,我们看到TemplateBinding只能绑定依赖属性
企业微信截图_17344140077776.png

然后我们再随便找个控件看一下它的属性定义
image.png

image.png

image.png

image.png

会发现,其实这些控件的大多数属性在定义上都是依赖属性呢!

  • UIPropertyMetadata:该类型有三个参数
    defaultValue:依赖属性默认值
    propertyChangedCallback:依赖属性值变化回调函数,在属性值实际被修改后触发,用来处理属性变更后事情。
    coerceValueCallback:依赖属性值变化强制回调函数,在属性值被设置前触发,用来验证和修正新值
 public partial class PilotLamp : UserControl
 {
     public PilotLamp()
     {
         InitializeComponent();
     }

     /// <summary>
     /// 指示灯的颜色
     /// </summary>
     public PilotLampColor PilotLampColor
     {
         get { return (PilotLampColor)GetValue(PilotLampColorProperty); }
         set { SetValue(PilotLampColorProperty, value); }
     }

     public static readonly DependencyProperty PilotLampColorProperty =
     DependencyProperty.Register("PilotLampColor", typeof(PilotLampColor), typeof(PilotLamp), new UIPropertyMetadata(PilotLampColor.Green, PilotLampColorPropertyChanged));

     private static void PilotLampColorPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs arg)
     {
         PilotLamp Control = obj as PilotLamp;
         Control.ChangeStatus();
           // string Data = (string)arg.NewValue;
            //Control.btn.Content = Data;
     }

     private void ChangeStatus()
     {
        // other
     }

 }

二:附加属性(Attached Properties)

附加属性允许你将属性附加到任何对象上,而不仅仅是该类本身的实例。这允许开发者定义可以在任何元素上使用的属性,而不需要继承自该元素的类。附加属性通常用于控件模板、样式或布局中,以提供额外的功能或信息。

  • 声明附加属性
    附加属性也是基于DependencyProperty的,但是它们通过静态Get和Set方法而不是普通的CLR属性访问器来访问。例如:
public static readonly DependencyProperty MyAttachedPropertyProperty = DependencyProperty.RegisterAttached(  
    "MyAttachedProperty", typeof(string), typeof(MyAttachedProperties), new PropertyMetadata(default(string)));  
  
public static void SetMyAttachedProperty(DependencyObject element, string value)  
{  
    element.SetValue(MyAttachedPropertyProperty, value);  
}  
  
public static string GetMyAttachedProperty(DependencyObject element)  
{  
    return (string)element.GetValue(MyAttachedPropertyProperty);  
}

在这个例子中,MyAttachedProperty是一个附加属性,它可以通过SetMyAttachedProperty和GetMyAttachedProperty方法附加到任何DependencyObject上。

  • 实战使用:
    我们添加一个静态类,给它添加一个附加属性ImageSource,并在使用Button时通过ControlTemplate进行重组时进行附加属性绑定。
    定义部分:
    public static class JSCProperties
    {
        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.RegisterAttached("ImageSource", typeof(ImageSource), typeof(JSCProperties), new PropertyMetadata(null));

        public static void SetImageSource(DependencyObject element, ImageSource value)
        {
            element.SetValue(ImageSourceProperty, value);
        }

        public static ImageSource GetImageSource(DependencyObject element)
        {
            return (ImageSource)element.GetValue(ImageSourceProperty);
        }
    }

buttonStyle部分

    <Window.Resources>
        <Style x:Key="buttonStyle" TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border>
                            <StackPanel>
                                <Image Width="50" Stretch="Uniform" Height="50" Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(local:JSCProperties.ImageSource)}"/>
                                <TextBlock Text="{TemplateBinding Content}" FontSize="18" TextAlignment="Center"/>
                            </StackPanel>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

使用部分

    <Grid>
        <Button local:JSCProperties.ImageSource="/Images/next.png" Content="按钮" Width="100" Height="80" Style="{StaticResource buttonStyle}"/>
    </Grid>

呈现效果

image.png

依赖属性和普通属性

区别很多,这里只讲我目前用到的绑定数据

  • 依赖属性:可以进行数据绑定,也就是只有控件的依赖属性才可以使用Binding
  • 普通属性:不可以进行数据绑定(Binding),否则会报错。
    测试数据绑定如下
    d7c76491-0876-4375-98e6-22d7050b3b57.png

    5476c2a5-b1b8-4117-93da-7f9815ab5257.png

    ebf49805-4a17-4df9-b71d-28bdcf71a25e.png

    6e82ad00-5efe-49f7-8ea0-1018e37f8c3b.png

    测试WPF 的依赖属性系统内置了对属性值变化的通知支持如下
    image.png

    image.png

    image.png

    image.png

    image.png

    发现,一旦改变nsme1,UCControl1中的Button也会随着进行改变,所以可以得出
    WPF 的依赖属性系统内置了对属性值变化的通知

总结
依赖属性:是WPF特有的,用于支持数据绑定、样式、动画等高级功能。它们通常用于控件类,但也可以用于任何继承自DependencyObject的类。
附加属性:允许你将属性附加到任何DependencyObject上,而不仅仅是该属性的定义类。这提供了一种灵活的方式来在不修改类继承层次结构的情况下扩展类的功能。
这两种属性在WPF开发中非常有用,它们极大地增强了WPF应用程序的灵活性和可定制性。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 什么是Xaml Xaml(Extensible Application Markup Language) 可扩展应...
    北风知我意阅读 681评论 0 1
  • 目录 什么是WPF? WPF的历史? 为什么要用WPF及WPF作用 WPF与winForm区别? 什么是WPF? ...
    灬52赫兹灬阅读 5,884评论 2 11
  • 本文章切绍以下内容1.WPF依赖属性[#WPF%E4%BE%9D%E8%B5%96%E5%B1%9E%E6%80%...
    Elvis523阅读 1,246评论 0 1
  • 认知尚浅,如有错误,愿闻其详!   起初,对依赖属性是一点都不了解的,完全不明白其用意何在,他的出发点在哪。看了很...
    Memoyu阅读 1,211评论 0 1
  • VS2015 git不支持ssh协议 遇到编译报错的问题,有的时候重启下vs也许就能解决 Windows: 程序的...
    清水包哟阅读 962评论 0 0