加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 20:13:39 所属栏目:百科 来源:网络整理
导读:1、一个依赖对象示例: public class MyDendencyControl : MyDependencyObject { public static readonly MyDependencyProperty ContentDependencyProperty = MyDependencyProperty.Register("Content",typeof(string),typeof(MyDendencyControl),new MyProp

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.52php.cn/article/p-etgyvuhf-bcq.html

特别感谢。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读