• 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

  • 相关阅读:
    异常日志以及非异常日志记录方法
    oracle 监测数据库是否存在指定字段
    listview禁止双击一条之后选中复选框按钮的方法
    oracle 的rowid和rownum
    修改文件的名字的写法
    使用C#读取XML节点,修改XML节点
    BZOJ 1004: [HNOI2008]Cards
    P5022 旅行 (NOIP2018)
    P5021 赛道修建 (NOIP2018)
    P5020 货币系统 (NOIP2018)
  • 原文地址:https://www.cnblogs.com/DebugLZQ/p/3152922.html
Copyright © 2020-2023  润新知