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 这个函数就是用来在通知之后执行的。这样我们可以在自定义控件初始化的时候加载资源,当依赖属性发生变化时,会触发事件,
我们回调至这个函数就能达到效果。结果将会界面上实时显示
经过测试!上面这种方法不安全。不知道什么问题造成的。初始值经常会覆盖设置的值。不知道有没有人有办法彻底解决。