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

前端之家收集整理的这篇文章主要介绍了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",new PropertyMetadata(Brushes.Transparent,PropertyChanged));
        public static readonly DependencyProperty MouSEOverColorProperty = DependencyProperty.Register("MouSEOverColor",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 这个函数就是用来在通知后执行的。这样我们可以在自定义控件初始化的时候加载资源,当依赖属性发生变化时,会触发事件,

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



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

猜你在找的设计模式相关文章