照书学WPF之 Dependency Property 1

简介

Dependency Property: 它们依赖一些其他的property和外在的影响,引起自身的变化.

如: WPF框架的编程经常和界面打交道,经常遇到的一个情况是某个属性的值的变化会影响到多个其他对象。比如当一个Button的改变大小超过了它的容器,他的容器应该自动调整大小。于是我们考虑在每个属性的set方法中触发一些事件,但很快我们发现现有的功能很难满足我们的需求,至少不能简洁漂亮的满足这些需求。

 定义示例: public static readonly DependencyProperty FontSizePropery;

1.简单的element tree

 通过简单的例子来理解"沿袭"(不能说是继承)

窗口构造函数将Font size 初使化为16设备无关的单位. 所有的BUTTON都会沿袭这个设置(都是WINDOW的孩子)

Code

 element tree是我们能看到的(实际)能看到的视觉对像, 是对logic tree的简单处理,更容易理解程序 (font size如何被处理的), 在此程序中为window->grid->(button collection)->(textblock collection)

特点:树中较低的对像"沿袭"父亲的property,然而如果某个对像有明确的设定自己的font size,那么就不用沿袭父亲的这个property

注: Grid根本就没有fontsize property,但依然可以沿袭(内部机制,不是很明白)

 property set priority: 对像自己的设定> 沿袭来的值 > 默认值

 

2. dependecy property 示例

在WPF中,dependency property的使用,允许以一般的方式自动进行大部分的通知.

定义:  public static readonly DependencyProperty SpaceProperty;

它是public and static, 此成员只与类相关,而非与对象相关联.

注册:  SpaceProperty =  DependencyProperty.Register.("Name", typeof(datatype), typeof(ownertype));

实际上这个property不可以简单的这么完成,还要须要元数据等元素,并且由于是静态的成员,必须在静态构造函数中初使化

static SpaceButton()
        {
            //define metadata
            FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata();
            metadata.DefaultValue = 1;
            metadata.AffectsMeasure = true;
            metadata.Inherits = true;
            metadata.PropertyChangedCallback += OnSpacePropertyChanged;

            //Register dependency property
            SpaceProperty = DependencyProperty.Register("Space", typeof(int), typeof(SpaceButton),
                metadata, ValidateSpaceValue);

        }

ValidateSpaceValue: 检验值是否合法

AffectsMeasure: 影响控件的尺寸调整.

使用: .Net CLR wrapper

public int Space
        {
            set { SetValue(SpaceProperty, value); }
            get { return (int)GetValue(SpaceProperty); }

        }

注意:即使传到SetValue and GetValue方法内当参数的property的对象是静态的,而这两个方法却是实例方法, 它们的值的设定和取得都和特定的实例有关, 这个property维持目前的值,且处理所有的日常事务.

完整示例:

Code

[Question]Logical tree, Visual tree, will trace it in the next

 

 

posted @ 2009-04-18 23:39  refeiner  阅读(373)  评论(0编辑  收藏  举报