码迷,mamicode.com
首页 > 其他好文 > 详细

依赖属性

时间:2016-12-31 15:51:43      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:方法   例子   ble   property   exp   table   set   全局   数据   

依赖属性基础

  依赖属性是具有借用其他对象的数据的能力,具有依赖属性的对象为依赖对象。WPF所有UI都是依赖对象。

只有依赖属性才能做为Bingding的源或目标。

DependencyObject具有GetValue()和SetValue()两个方法。

自定义一个依赖对象

 public class Student3: DependencyObject//必须继承DependencyObject才能成为一个依赖对象

    {

        // 定义依赖属性标准格式

        public static readonly DependencyProperty NameProperty =

            DependencyProperty.Register("Name", typeof(string), typeof(Student3), new PropertyMetadata("无名"));

        //Name是依赖属性NameProperty的包装器,对外暴漏被使用

        public string Name//VS中输入propdp再按两次tab可以快捷输入

        {

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

            set { SetValue(NameProperty, value); }

        }

 

 

        //使其也像UI一样有个SetBingding方法

        public BindingExpressionBase SetBingding(DependencyProperty dp, BindingBase binding)

        {

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

        }

    }

 

调用:

    public partial class property : Window

    {

        //一定要定义在外面,要不然textBox1改变了textBox2也不会自动

        Student3 su = new Student3();

        public property()

        {

            InitializeComponent();

 

           

            su.SetBingding(Student3.NameProperty, new Binding("Text") { Source = textBox1 });

            //Student3没为实现INotifyPropertyChanged接口同样也可以得到通知

            textBox2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = su  });

        }

    }

 

其实依赖属性的值并不是保存在NameProperty 中,而是通过CLR属性名和宿主类型名称从全局的Hashtable中检索或保存的。

 

 

附加属性基础

附加属性本质还是依赖属性。一个对象在不同环境后才具有的属性就叫附加属性。

如人类Human在学校有班级属性,在公司就有部门的属性。

 <Label x:Name="label" Grid.Row="1"/>

 

定义以及使用例子:

public class Human : DependencyObject

    {

        //一定要继承DependencyObject成为依赖对象

    }

 

    public class School : DependencyObject

    { 

        // 标准定义格式,与信赖属性差不多。 使用“propa”+两次tab可以快捷生成

        public static readonly DependencyProperty GradeProperty =

            DependencyProperty.RegisterAttached("Grade", typeof(string), typeof(School), new PropertyMetadata("无班级"));

        public static string GetGrade(DependencyObject obj)

        {

            return (string)obj.GetValue(GradeProperty);

        }

 

        public static void SetGradeP(DependencyObject obj, string value)

        {

            obj.SetValue(GradeProperty, value);

        }

 }

 

调用:

 Human human = new Human();

            School.SetGrade(human, "五年级");

 

            string grade = School.GetGrade(human);

            //可以得到grade的值为五年级

依赖属性

标签:方法   例子   ble   property   exp   table   set   全局   数据   

原文地址:http://www.cnblogs.com/evemen/p/6239321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!