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