模拟实现WPF的依赖属性及绑定通知机制(4)--模拟实现绑定连动机制 .

来源:互联网 发布:网络教育文凭考公务员 编辑:程序博客网 时间:2024/04/29 02:25
 

1、一个依赖对象示例:

 public class MyDendencyControl : MyDependencyObject
    {
        public static readonly MyDependencyProperty ContentDependencyProperty =
            MyDependencyProperty.Register("Content", typeof(string), typeof(MyDendencyControl), new MyPropertyMetadata("hello"));

        //封装成普通属性的依赖属性,注意调用的是基类的相关方法。
        public string Content
        {
            get
            {
                return base.GetValue(ContentDependencyProperty).ToString();
            }
            set
            {
                base.SetValue(ContentDependencyProperty, value);
            }
        }
    }

2)一个实现了INotifyPropertyChanged接口的数据提供类
    public class MyNotifyPropertyClass : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged(string PropertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
            }
        }
        private string _Name;
        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                if (_Name != value) //这是比较好的习惯,可以提供性能.
                {
                    _Name = value;
                    RaisePropertyChanged("Name");
                }
            }
        }
    }

3、测试连动(应用)

//创建一个依赖对象实例
            MyDendencyControl theCtrl = new MyDendencyControl();
            //创建一个绑定目标类
            MyNotifyPropertyClass theClass = new MyNotifyPropertyClass();
            //构建绑定,这种是手工绑定方法,在xaml中设置,最终也会解释成如下代码:
            MyBinding theBinding = new MyBinding();
            theBinding.TargetObject = theClass;
            theBinding.PropertyName = "Name";
            theCtrl.SetBinding(MyDendencyControl.ContentDependencyProperty, theBinding);
            //默认值
            MessageBox.Show(theCtrl.Content);
            theClass.Name = "hello,you are good!";
            //关联属性变化后再看当前值
            MessageBox.Show(theCtrl.Content);
            //依赖属性变化,会通知关联类属性也变化.
            theCtrl.Content = "are you ready?";
            MessageBox.Show(theClass.Name);

到此,微软的WPF依赖属性,绑定和通知属性及相互连动机制就完成了,当然,只是简单的模拟。微软的实现还是要复杂很多,但原理基本如此

 

转载地址:

http://blog.csdn.net/hawksoft/article/details/6726245

特别感谢。

原创粉丝点击