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

1 篇文章 0 订阅

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

依赖属性

".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前面的博文: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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值