WPF 自定义的依赖属性要想在界面上能立即看到属性变化的值。必须实现回调通知
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 这个函数就是用来在通知之后执行的。这样我们可以在自定义控件初始化的时候加载资源,当依赖属性发生变化时,会触发事件,