WPF整理-为User Control添加依赖属性

时间:2021-11-01 01:57:37

依赖属性

".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整理-为User Control添加依赖属性

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

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

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

为User Control添加依赖属性

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

WPF整理-为User Control添加依赖属性

连按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());

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++;
}

程序运行如下:

WPF整理-为User Control添加依赖属性

点击几次button

WPF整理-为User Control添加依赖属性