八. DependencyObject测试代码
通过上面的这幅图,我们知道它的主要功能包括:各种依赖属性的GetValue、SetValue操作(核心功能)和ClearValue、 CoerceValue、GetLocalValueEnumerator、ReadLocalValue等操作。为了测试这些功能,我们首先创建几个 类,第一个类X,内部首先注册一个附加依赖属性,我们都知道,不管是附加依赖属性还是依赖属性,都需要使用到GetValue和SetValue操作,只 是一个封装成了属性,而另一个封装成了静态方法而已。第二个类直接继承自我们前面在实现DependencyProperty时创建的 DependencyObject原型类。
1: class X {
2: @H_404_19@//注册一个附加依赖属性A
3: public static readonly DependencyProperty AProperty = DependencyProperty.RegisterAttached("A",typeof(int),255);">typeof(X));
4: //获取附加属性A的值
5: void SetA(DependencyObject obj,255);">int value)
6: {
7: obj.SetValue(AProperty,255);">value);
8: }
9: //设置附加属性A的值
10: int GetA(DependencyObject obj)
11: {
12: return (int)obj.GetValue(AProperty);
13: }
14: //注册一个附加依赖属性B
15: readonly DependencyProperty BProperty = DependencyProperty.RegisterAttached("B",255);">string),255);">typeof(X));
16: //设置附加属性B的值
17: void SetB(DependencyObject obj,255);">string value)
18: {
19: obj.SetValue(BProperty,255);">value);
20: }
21: //获取附加属性B的值
22: string GetB(DependencyObject obj)
23: {
24: string)obj.GetValue(BProperty);
25: }
26:
27: }
28:
29: class Y : DependencyObject {
30: }
class Z : DependencyObject
2: {
3: readonly DependencyProperty SimpleDPProperty =
4: DependencyProperty.Register("SimpleDP",255);">double),255);">typeof(Z),
5: new PropertyMetadata((double)0.0,
6: new PropertyChangedCallback(OnValueChanged),
7: new CoerceValueCallback(CoerceValue)),
8: new ValidateValueCallback(IsValidValue));
9:
10: double SimpleDP
11: {
12: get { double)GetValue(SimpleDPProperty); }
13: set { SetValue(SimpleDPProperty,255);">value); }
14: }
15:
16: private void OnValueChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
17: {
18: Console.WriteLine("当值改变时,我们可以做的一些操作,具体可以在这里定义: {0}",e.NewValue);
19: }
20:
21: object CoerceValue(DependencyObject d,255);">object value)
22: {
23: Console.WriteLine("对值进行限定,强制值: {0}",255);">value);
24: return value;
25: }
27: bool IsValidValue(value)
28: {
29: Console.WriteLine("验证值是否通过,如果返回True表示验证通过,否则会以异常的形式暴露: {0}",255);">value);
30: true;
31: }
32:
33: }