我正在实现一个布尔 DependencyProperty,当它设置为 true 时,它会向 DependencyObject 添加一个装饰器。我希望 DependencyProperty 的默认值为 true,但这样做不会触发 PropertyChangedCallback,因此默认情况下不会创建装饰器。有没有办法让 PropertyChangedCallback 在初始化时触发?
public static bool GetIsAdorned(DependencyObject obj)
{
return (bool)obj.GetValue(IsAdornedProperty);
}
public static void SetIsAdorned(DependencyObject obj, bool value)
{
obj.SetValue(IsAdornedProperty, value);
}
public static readonly DependencyProperty IsAdornedProperty =
DependencyProperty.RegisterAttached("IsAdorned",
typeof(bool),
typeof(UIElement),
new UIPropertyMetadata(true, OnIsAdornedChanged));
private static void OnIsAdornedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var uiElement = dependencyObject as UIElement;
var newValue = (bool)e.NewValue;
var adornerLayer = AdornerLayer.GetAdornerLayer(uiElement);
if (newValue)
{
adornerLayer.Add(new MyAdorner(uiElement));
}
}