WPF系列 —— 控件添加依赖属性

本文介绍了如何利用WPF的依赖属性功能,通过自定义一个TimePicker控件来实现时间选择的功能。通过创建依赖属性并进行绑定,可以实现在WPF应用中使用更灵活的时间选择器。

依赖属性的概念,用途 ,如何新建与使用。本文用做一个自定义TimePicker控件来演示WPF的依赖属性的简单应用。

先上TimePicker的一个效果图。

GIF

 

 

 

 

 

 

 

 

 

概念 和 用途:依赖属性是对传统.net 属性的一种封装,使一个传统.net属性支持 WPF 中的 数据绑定、动画、样式 等功能。

新建:任意代码代码文件中 ,输入 propdp 再双击tab键。生成如下的代码块。

     MyProperty: 依赖属性的名称; ownerclass: 当前依赖属性绑定的所有类; new PropertyMetadata 是依赖属性的初始化对象,这里0代表默认值。

public int MyProperty
{
    get { return (int)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}

// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));

使用:这里我们使用绑定绑定,稍后使用自定义控件的Time属性来介绍。

如何使用依赖属性构建一个带绑定的TimePicker自定义控件

新建一个项目名称为DependencyPropertyDemo的WPF 项目 image,新建一个TimePicker的自定义控件。Xaml布局如下:

<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="9*"/>
            <ColumnDefinition Width="24"/>
            <ColumnDefinition Width="10*"/>
        </Grid.ColumnDefinitions>
        <ComboBox Name="cbbHour" Grid.Column="0"/>
        <Label Content=":" Grid.Column="1"/>
        <ComboBox Name="cbbMinute" Grid.Column="2"/>
    </Grid>

BehindCode新建一个名称为Time的依赖属性,如下:

public string Time
        {
            get { return (string)GetValue(TimeProperty); }
            set { SetValue(TimeProperty, value); }
        }

        public static readonly DependencyProperty TimeProperty =
            DependencyProperty.Register("Time",
                typeof(string),
                typeof(TimePicker),
                new PropertyMetadata(defaultValue: "00:00", 
                    propertyChangedCallback: null,
                    coerceValueCallback: coerceValueCallback));

        private static object coerceValueCallback(DependencyObject d, object baseValue)
        {
            if (baseValue != null)
            {
                var control = d as TimePicker;
                var times = baseValue.ToString().Split(':');
                control.cbbHour.SelectedItem = times[0];
                control.cbbMinute.SelectedItem = times[1];
                return baseValue.ToString();
            }
            return baseValue;
        }

这里详细介绍一下PropertyMetadata的三个参数:defaultValue:默认值,不用介绍了;propertyChangedCallback:属性变化后的通知事件,这里不需要任何通知,所以传入null值;coerceValueCallback:这是属性值新值绑定时,通知事件,这里使用得到的值来给控件赋值。到这里Time依赖属性也就完成一半了。

TimePicker属性依赖属性Time的绑定

绑定方式很简单,如下图。若Time是一个普通的.net属性而非依赖属性的话,是不能这样使用绑定方式的。

<local:TimePicker HorizontalAlignment="Left" Margin="137,38,0,0" VerticalAlignment="Top" Width="161"
                          Time="{Binding StartTime,Mode=TwoWay}"/>

假设添加在TimePicker后台添加一个Code的普通属性,使用绑定的话,会出现如下的状况。

image

 

后话总结

依赖属性使用是有一定限制的,就是他注册的类对象,也就是上文的ownerclass必须继承DependencyObject 这个基类,不过不用担心,WPF大部分元素都间接的集成这个基类。

本文实现的TimePicker控件可以在一些情况下解决WPF下没有Time选择控件的问题。

Demo下载

如果,您认为阅读这篇博客让您有些收获,请点击下面的【推荐】和 【关注】按钮,感谢大家的支持,我是朝兮兮。眨眼

转载于:https://www.cnblogs.com/zhaoxixi/p/4947996.html

Microsoft's Windows Presentation Foundation (WPF) provides you with a development framework for building high-quality user experiences for the Windows operating system. It blends together rich content from a wide range of sources and allows you unparalleled access to the processing power of your Windows computer. Pro WPF 4.5 in C# provides a thorough, authoritative guide to how WPF really works. Packed with no-nonsense examples and practical advice you'll learn everything you need to know in order to use WPF in a professional setting. The book begins by building a firm foundation of elementary concepts, using your existing C# skills as a frame of reference, before moving on to discuss advanced concepts and demonstrate them in a hands-on way that emphasizes the time and effort savings that can be gained. What you’ll learn •Understand the fundamentals of WPF programming from XAML to controls and data flow. •Develop realistic application scenarios to see navigation, localization and deployment in action. •Explore the advanced user interface controls that WPF provides. •Learn to manage documents from within WPF: Text layout, printing, and document packaging are all covered. •Use graphics and multimedia to add punch to your applications Who this book is for This book is designed for developers encountering WPF for the first time in their professional lives. A working knowledge of C# and the basic architecture of .NET is helpful to follow the examples easily, but all concepts will be explained from the ground up. Table of Contents 01.Introducing WPF 02.XAML 03.Layout 04.Dependency Properties 05.Routed Events 06.Controls 07.The Application 08.Element Binding 09.Commands 10.Resources 11.Styles and Behaviors 12.Shapes, Brushes, and Transforms 13.Geometries and Drawings 14.Effects and Visuals 15.Animation Basics 16.Advanced Animation 17.Control Templates 18.Custom Elements 19.Data Binding 20.Formatting 21.Bound Data 22.Data Views 23.Lists, Trees, and Grids 24.Windows Pages and Navigation 25.Menus, Toolbars, and Ribbons 26. Sound and Video 27.3-D Drawing 28.Documents 29. Printing 30.Interacting with Windows Forms 31.Multithreading 32.The Add-in Model 33.ClickOnce Deployment ----------------------------------------------------------- Pro WPF 4th edition,喜欢的朋友请支持正版。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值