加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 22:15:51 所属栏目:百科 来源:网络整理
导读:WPF 自定义的依赖属性要想在界面上能立即看到属性变化的值。必须实现回调通知 下面以最近刚自定义的RadioButton为例 public class RadioButton360 : RadioButton { public static readonly DependencyProperty CheckedColorProperty = DependencyProperty.Re

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

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



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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读