XAML(2)

 3.依赖属性

    在用WPF编程时,常常会遇到"依赖属性"这个术语。WPF元素是带有方法,属性和事件的类。WPF元素的几乎每个属性都是依赖属性, 这是什么意思?依赖属性可以依赖其他输入,例如主题和用户喜好。依赖属性与数据绑定,动画,资源和样式一起使用

    前面我们说过WPF的体系结构,只有派生自DependencyObject基类的类才能包含依赖属性。

    (由于DependencyObject类位于层次结构的最高层,所以每个WPF元素都派生自这个基类)

    下面写一个类自定义依赖属性

    

 class CustomClass:DependencyObject
    {

        //CLR属性进行封装
        public string Name
        {
            get { return (string)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }

        //定义依赖属性
        public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(CustomClass));
        
    }

   上面的类定义了一个依赖属性NameProperty和一个Name属性

   依赖属性使用Register()方法通过WPF依赖属性系统来注册。Register()方法可以获取依赖属性的名称,依赖属性的类型和拥有者的类型。使用DependencyObject基类的SetValue()方法,可以设置依赖属性的值,使用GetValue()方法可以获取其值。

   CustomClass cs = new CustomClass();

   cs.SetValue(CustomClass.NameProperty, txtBox1.Text);

   txtBox2.Text = (string)cs.GetValue(CustomClass.NameProperty);

实例化自定义类,设置和取得依赖属性的值

WPF的控件的属性都带有依赖属性,所以对属性进行设置

下面是设置一个Button的依赖属性

//通过包装的属性设置按钮的背景颜色
buttonA.Background = new SolidColorBrush(Colors.Red);

//通过依赖性属性的SetValue设置按钮的背景颜色
SolidColorBrush brush = new SolidColorBrush(Colos.Blue);
buttonB.SetValue(Button.BackgroundProperty,brush);


//通过包装的属性获取ButtonB的背景颜色
SolidColorBrush brush1 = (SolidColorBrush)(ButtonA.Background);
txt_Value1.Text = brush1.Color.ToString();

//通过依赖性属性的GetVaue获取ButtonB的背景颜色
SolidColorBrush brush2 = (SolidColorBrush)(ButtonB.GetValue(Button.BackgroundProperty));
txt_Value2.Text = b_Brush2.Color.ToString();

MSDN中给出了下面几种应用依赖属性的场景:

  1. 希望可在样式中设置属性。

  2. 希望属性支持数据绑定。

  3. 希望可使用动态资源引用设置属性。

  4. 希望从元素树中的父元素自动继承属性值。

  5. 希望属性可进行动画处理。

  6. 希望属性系统在属性系统,环境或用户执行的操作或者读取并使用样式更改了属性以前的值时报告。

  7. 希望使用已建立的,WPF进程也使用的元数据约定,例如报告更改属性值时石佛要求布局系统重新编写元素的可视化对象。

下面会写几个实际的场景应用

原文地址:https://www.cnblogs.com/hdsong/p/5061452.html