WPF依赖项属性详解一

WPF使用更加高级的依赖项属性(dependency property)替换了原来的.net 属性.

一.定义依赖属性:

 第一步定义表示属性的对象,它是DependencyProperty类的一个实例,对于创建的依赖属性,要随时获得化的信息,甚至可能在多个类之间共享这些信息,因此必须将依赖属性字段设置为静态

例如有一个frameworkElement类的依赖属性 MakedCounty,依赖属性约定名称是在普通属性的后面加上Property

 public  class frameworkElement:UIElement{

  public static readonly DependencyProperty MakedCountyProperty;

}

二.注册依赖属性:

 WPF确保DePendencyProperty类不能被实例化,只能通过register()方法创建DependencyProperty实例.同时WPF还确保DePendencyProperty对象在创建后不能被修改,因此只能通过register的方法参数还进行赋值.

public class Button:ButtonBase
{
  //依赖属性
  public static readonly DependencyProperty IsDependencyProperty;

  static Button()
  {
    //注册依赖属性
    Button.IsDependencyProperty = DependencyProperty.Register("IsDefault",
      typeof(bool), typeof(Button),
      new FrameworkPropertyMetadata(false,
      new PropertyChangedCallback(OnIsDefaultChanged)));
  }
  //.NET属性(可选)
  public bool IsDefault
  {
    get { return (bool)GetValue(Button.IsDefaultProperty); }
    set { SetValue(Button.IsDefaultProperty, value); }
  }

  //属性改变时的回调
private static void OnIsDefaultChanged(DependencyObject o,DependencyPropertyChangedEventArgs e)
  {...}
}

原文地址:https://www.cnblogs.com/wuxigang/p/2673854.html