WPF学习笔记--xaml属性介绍

来源:互联网 发布:91家居软件 编辑:程序博客网 时间:2024/05/29 14:05

 一、Dependency属性

 Dependency属性最大的特点就是内建的变化通知功能。

提供Dependency属性功能主要是为了直接在声明标记的时候就提供丰富的功能。WPF声明的友好设计的关键是大量的使用属性。如果没有Dependency属性,我们将编写大量的代码来实现属性所展示的功能。

      1、变化通知功能:属性的值被改变后,通知界面进行更新。

      2、属性值的继承功能:子元素将继承父元素中对应属性名的值。

      3、支持多个提供对象:我们可以通过多种方式来设置Dependency属性的值。

先看一个例子:

public class Button : ButtonBase

{

   // 申名了一个dependency静态属性

   public static readonly DependencyProperty IsDefaultProperty;

   static Button()

   {

      // 注册这个属性到Button中

      Button.IsDefaultProperty = DependencyProperty.Register(“IsDefault”,  typeof(bool), typeof(Button),

            new FrameworkPropertyMetadata(false,

            new PropertyChangedCallback(OnIsDefaultChanged)));

            …

   }

   // 属性缺省

   public bool IsDefault

   {

         get { return (bool)GetValue(Button.IsDefaultProperty); }

         set { SetValue(Button.IsDefaultProperty, value); }

   }

   //属性改变的时候要调用的方法

   private static void OnIsDefaultChanged(

   DependencyObject o, DependencyPropertyChangedEventArgs e) { … }

   …

}

 

在上面的实现代码中,System.Windows.DependencyProperty类表示的静态字段IsDefaultProperty才是真正的Dependency属性。为了方便,所有的Dependency属性都是公有、静态的,并且还有属性后缀。通常创建Dependency属性可用静态方法DependencyProperty.Register。参数的属性名称、类型、使用这个属性的类。并且可以根据重载的方法提供其他的通知事件处理和默认值等等。

 

待续............