WPF 自定义控件依赖属性怎么实时变化?

WPF 自定义的依赖属性要想在界面上能立即看到属性变化的值。必须实现回调通知


下面以最近刚自定义的RadioButton为例


public class RadioButton360 : RadioButton
    {
        public static readonly DependencyProperty CheckedColorProperty = DependencyProperty.Register("CheckedColor", typeof(Brush), typeof(RadioButton360), new PropertyMetadata(Brushes.White, PropertyChanged));
        public static readonly DependencyProperty UnCheckedColorProperty = DependencyProperty.Register("UnCheckedColor", typeof(Brush), typeof(RadioButton360), new PropertyMetadata(Brushes.Transparent, PropertyChanged));
        public static readonly DependencyProperty MouseOverColorProperty = DependencyProperty.Register("MouseOverColor", typeof(Brush), typeof(RadioButton360), new PropertyMetadata(Brushes.LightGray, PropertyChanged));

        /// <summary>
        /// 选中颜色
        /// </summary>
        public Brush CheckedColor
        {
            get { return (Brush)GetValue(CheckedColorProperty); }
            set { SetValue(CheckedColorProperty, value); }
        }

        /// <summary>
        /// 未选中颜色
        /// </summary>
        public Brush UnCheckedColor
        {
            get { return (Brush)GetValue(UnCheckedColorProperty); }
            set { SetValue(UnCheckedColorProperty, value); }
        }

        /// <summary>
        /// 鼠标移动颜色
        /// </summary>
        public Brush MouseOverColor
        {
            get { return (Brush)GetValue(MouseOverColorProperty); }
            set { SetValue(MouseOverColorProperty, value); }
        }

        public RadioButton360()
        {
            try
            {
                this.Resources.Source = new Uri("DialogEx;Component/Controls/RadioButton360.xaml", UriKind.RelativeOrAbsolute);
            }
            catch
            {
                throw new Exception("未找到:DialogEx;Component/Controls/RadioButton360.xaml");
            }
        }
        private static void PropertyChanged(DependencyObject dobj, DependencyPropertyChangedEventArgs e)
        {
            RadioButton360 control = (RadioButton360)dobj;
            control.Resources["CheckedColor"] = control.CheckedColor;
            control.Resources["UnCheckedColor"] = control.UnCheckedColor;
            control.Resources["MouseOverColor"] = control.MouseOverColor;
            control.Style = control.Resources["RadioButtonStyle"] as Style;
            //String.Format("PropertyChanged - 属性:{0} 新值:{1} 旧值:{2}", e.Property.Name, e.NewValue, e.OldValue);
        }

PropertyChanged 这个函数就是用来在通知之后执行的。这样我们可以在自定义控件初始化的时候加载资源,当依赖属性发生变化时,会触发事件,

我们回调至这个函数就能达到效果。结果将会界面上实时显示



经过测试!上面这种方法不安全。不知道什么问题造成的。初始值经常会覆盖设置的值。不知道有没有人有办法彻底解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值