为User Control添加依赖属性
2018-03-01 10:22
113 查看
依赖属性
".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系统中相当底层的一个基类,如下:
![](https://images0.cnblogs.com/blog/281227/201306/24174933-4a09d8b082234ed49828a722cdd1f28e.png)
从这颗继承树可以看出,WPF的所有UI控件都是依赖对象。WPF的类库在设计时充分利用了依赖属性的优势,UI空间的绝大多数属性都已经依赖化了。
有些时候,我们需要为我们自定义的类或控件等添加依赖属性。
DebugLZQ前面的博文:WPF 自定义依赖属性 介绍了如何为自定义的类添加依赖属性;这篇博文以前面的博文为基础,介绍如何为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中使用,添加这个映射
<Window x:Class="CreatingADependencyProperty.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:CreatingADependencyProperty"我们用Binding使用如下:
<StackPanel> <local:SimpleControl x:Name="_simple"/> <TextBlock Text="{Binding YearPublished,ElementName=_simple}" FontSize="30"/> <Button Content="Change Value" FontSize="20" Click="OnChangeValue"/> </StackPanel>Click事件如下
private void OnChangeValue(object sender, RoutedEventArgs e) { _simple.YearPublished++; }程序运行如下:
点击几次button
相关文章推荐
- WPF整理-为User Control添加依赖属性
- WPF整理-为User Control添加依赖属性
- 自定义Panel中添加依赖属性需要注意的问题
- 自定义Panel中添加依赖属性需要注意的问题
- Android Studio 添加第三方依赖后,控件属性不提示
- 在Silverlight自定义控件中添加依赖属性
- wp7 webbrowser 添加依赖属性content
- DirectX编程属性需要添加的依赖项
- 自定义Panel中添加依赖属性需要注意的问题
- OkHttp添加依赖后仍然使用不了的情况结局
- 在属性上面添加这个注释 在unity界面能看到注释内容
- [转]WPF 学习笔记4 依赖属性
- 依赖属性(Dependency Properties)基础
- dom4j创建XML添加属性和标签和内容添加CDATA 删除属性
- VS2005 C++ 项目怎样添加“依赖”、“库目录”和“包含目录”
- sharepoint 2013 部署步骤“添加解决方案”中出现错误: 已在此服务器场中安装 ID 为{guid}的功能。请使用强制属性显式地重新安装此功能。
- supermap 在地图上显示 属性信息(添加图层)
- Maven的pom文件中依赖的 <classifier>属性
- DropDownList添加新项和设置只读属性
- 用javascript在对象中添加属性