WPF-依赖项属性简介

        WPF创建了一个新的依赖项属性系统,重写了传统的.NET属性以提高性能并集成新的功能(例如:数据绑定和动画)

        优点:效率更高的保存机制,支持附加功能(更改通知、属性值继承)。

        用法与普通属性相同,原因是使用普通属性的过程进行了封装。

写法结构

        public int 依赖项
        {
            get { return (int)GetValue(依赖项Property); }
            set { SetValue(依赖项Property, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty 依赖项Property =
            DependencyProperty.Register("依赖项Property", typeof(int), typeof(元素类), new PropertyMetadata(default(int)) { CoerceValueCallback = 强制验证方法},验证方法);

        private static bool 验证方法(object value)
        {
            throw new NotImplementedException();
        }

        private static object 强制验证方法(DependencyObject d, object baseValue)
        {
            throw new NotImplementedException();
        }

共享的依赖项属性

        子类与父类共享依赖项属性

        在子类中通过调用DenpendencyProperty.AddOwner()重用依赖项属性

子类类型.子类依赖项Property = 父类类型.父类依赖项Property.AddOwner(typeof(子类类型));

附加的依赖项属性

        注册的时候方法由Register(),改变为使用RegisterAttached()

        public static readonly DependencyProperty 依赖项Property =
            DependencyProperty.RegisterAttached("依赖项Property", typeof(int), typeof(元素类), new PropertyMetadata(0));

        其中两个关键的方法 SetValue() 和 GetValue() ,实现了控制反转的效果。

        本来由Grid设置子元素位置的方法,变成由子元素设置Grid位置属性的方法。

        例如:将Grid.SetRow(element,0) 包装成 element.SetValue(Grid.RowProperty,0)

属性验证的流程

        为了应对错误设置属性的可能性

        WPF属性验证的流程基本如下:

        第一步:强制回调CoerceValueCallback,处理同对象内依赖项属性值冲突的问题,修改或拒绝新值。应用场景,比如最小/大值的设定校验。

        第二步:验证回调ValidateValueCallback,校验新值的合法性,提供新值的生效结果True/False,这里不可检查其他属性值。

        第三步:触发PropertyChangedCallback。

        引申一个关于ScrollBar强制回调的对象内依赖项属性值的关系处理的思路。

        思路:先以Minimum为主,依次强制Maximum和Value的属性值使其合理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值