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

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://www.jb51.cc/article/p-etgyvuhf-bcq.html

特别感谢。

相关文章

什么是设计模式一套被反复使用、多数人知晓的、经过分类编目...
单一职责原则定义(Single Responsibility Principle,SRP)...
动态代理和CGLib代理分不清吗,看看这篇文章,写的非常好,强...
适配器模式将一个类的接口转换成客户期望的另一个接口,使得...
策略模式定义了一系列算法族,并封装在类中,它们之间可以互...
设计模式讲的是如何编写可扩展、可维护、可读的高质量代码,...