WPF中DependencyObject使用

来源:互联网 发布:注册淘宝店铺要多少钱 编辑:程序博客网 时间:2024/05/28 03:03

1.声明依赖对象    输入propdp +tab tab

2.例:

class Student : DependencyObject{

public string Name{

get{ return (string)GetValue(NameProperty); }

set{ SetValue(NameProperty,value); }

}

public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name",typeof(string),typeof(Student),new PropertyMetadadta(""));

public BindingExpressionBase SetBinding(DependencyProperty dp,BindingBase binding){

return BindingOperations.SetBinding(this,dp,binding);

}

}


PropertyMetadata为Defaultmetadata赋值

CoerceValueCallBack 依赖属性被强制改变时调用

DefalutValue

IsSealed PropertyMetadata是否可被更改

PropertyChangedCallback 依赖属性值改变时调用


DependencyProperty

包含一个 private static Hashtable PropertyFromName = new Hashtable();全局的Hashtable,它就是注册DependencyProperty 实例的地方。

DependencyProperty.Register(...)中最后是调用DependencyProperty.RegisterConnmon(...)


private static DependencyProperty RegisterCommon(string name,Type propertyType,Type ownerType,PropertyMetadata defaultMetadata,ValidateValueCallback validateValueCallback)


RegisterCommon :

FromNameKey key = new FromNameKey (name,ownerType); //它是一个.Net Framework的内部数据类型

FromNameKey(...){

_name = name;

_ownerType = ownerType;

_hashCode = _name.GetHashCode()^ownerType.GetHashCode();//hashcode 实际上是name和ownerType进行异或。

}

然后对key进行校验         if( PropertyFromName.Contains(key)) {throw...}

最后创建DependencyProperty 实例,并注册到PropertyFromName 这个Hashtable中

PropertyFromName[key] = dp;//dp是新创建的DependencyProperty实例


简单的说DependencyProperty 先用属性名和宿主的hashcode生成自己key的hashcode然后创建DependencyProperty 实例,最后在PropertyFromName

这个全局的hashtable中注册。


DependencyObject 的SetValue和GetValue方法

public object GetValue( DependencyObject dp){

//对dp进行有效性验证

this.VerifyAccess();

if(dp == null){

throw new ArgumentNullException("dp");

}

return GetValueEntry( LookupEntry(dp.GlobalIndex),dp,null,RequestFlage.FullyResolved ).Value;

}


GetValueEntry(...){...}

EntryIndex entryIndex = LookupEntry(dp.GloballIndex);

EffectiveValueEntry valueEntry = GetValueEntry(entryIndex,dp,null,RequestFlags.FullyResolved);

return valueEntry.Value;

//其实entryIndex和GlobalIndex都是之前那个Hashtable中的一个哈希码,

//通过这个HashCode找到valueEntry再从中取出value

DependencyObject 中包含一个 EffectiveValueEntry[] _effectValues数组用来存储valueEntry

GetValue从valueEntry中找到索引,然后根据索引在Hashtable中找dp.



附加属性 propa+ tab,tab

..........RegisterAttached(........,new UIPropertyMethodIO(0));


使用

School.SetGrade(stu,6);