博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WPF整理-为User Control添加依赖属性
阅读量:6947 次
发布时间:2019-06-27

本文共 1448 字,大约阅读时间需要 4 分钟。

原文:

依赖属性

".NET properties are nothing more than syntactic sugar over set and get methods."

我们知道.NET的属性只不过是get/set方法的语法糖衣。

"Dependency properties are the workhorse of WPF. This infrastructure provides for many of WPF's features, such as data binding, animations, and visual inheritance. In fact, most of the various element properties are Dependency Properties. Sometimes we need to create such properties for our own controls or windows."

依赖属性这个基础架构为我们提供了实现WPF诸多特性的基础,如数据绑定、动画等。

DependencyObject和DependencyPorperty两个类是WPF属性系统的核心。DependencyObject是WPF系统中相当底层的一个基类,如下:

从这颗继承树可以看出,WPF的所有UI控件都是依赖对象。WPF的类库在设计时充分利用了依赖属性的优势,UI空间的绝大多数属性都已经依赖化了。

有些时候,我们需要为我们自定义的类或控件等添加依赖属性。

DebugLZQ前面的博文: 介绍了如何为自定义的类添加依赖属性;这篇博文以前面的博文为基础,介绍如何为User Control添加Dependency Property。

为User Control添加依赖属性

1.首先定义一个名为SimpleControl的UserControl;在SimpleControl.xaml.cs中键入"propdp"

连按2次Tab,修改依赖属性名为YearPublishedProperty,属性包装名为YearPublished,默认值为2013。最终如下:

public int YearPublished{    get { return (int)GetValue(YearPublishedProperty); }    set { SetValue(YearPublishedProperty, value); }}        public static readonly DependencyProperty YearPublishedProperty =   DependencyProperty.Register("YearPublished", typeof(int), typeof(SimpleControl), new PropertyMetadata(2013));

2.为了能在XAML中使用,添加这个映射

 

我们用Binding使用如下:

Click事件如下

private void OnChangeValue(object sender, RoutedEventArgs e){     _simple.YearPublished++;}

程序运行如下:

点击几次button

 

转载地址:http://qwenl.baihongyu.com/

你可能感兴趣的文章
单机环境搭建Postgres-XC开发测试环境
查看>>
三: 推荐系统
查看>>
PHP文件上传-单文件上传函数
查看>>
jvmtop 监控
查看>>
使用JMH进行并发测试
查看>>
关于服务器 SAN 和 SDS
查看>>
ASP.NET 如何做出简单的验证码
查看>>
我的友情链接
查看>>
Spring 转换 model 为 json 时增加属性
查看>>
最新在线软件测试模拟题,做完答案立显,自我检测好机会!
查看>>
论坛PC端模板
查看>>
域名解析
查看>>
通过SNMP获取接口速率 32位与64位的区别
查看>>
Windows上用gcc编译SQLite3
查看>>
bash位置参数的简介
查看>>
VirtualBox导入其他虚拟机后网络问题
查看>>
Weblogic修改密码口令验证策略
查看>>
js 正则通过class查找Tag内的内容。
查看>>
ZeroClipboard实现多个浏览器兼容的复制文本到剪贴板的功能
查看>>
动态SQL、绑定变量、静态SQL的性能对比
查看>>