I’m implementing a boolean DependencyProperty that adds an adorner to the DependencyObject when it is set to true. I want the DependencyProperty’s default value to be true, but doing so does not fire the PropertyChangedCallback, so the adorner is not created by default. Is there a way to have the PropertyChangedCallback fire on initialization?
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));
}
}
Except for attached properties that support value inheritance, there is no default value that is automatically applied to all elements in a tree.
The value of a normal attached property (without inheritance) is not applied to any element unless you explicitly set that property. Getting the value of an attached property will return the default value from metadata when the property is not explicitly set on an element.
If you have for example an element in a Canvas without setting
Canvas.Left, the Canvas will get the default value forCanvas.Leftas 0 from metadata. The element itself simply does not have this value.So in your scenario you will have to apply
IsAdornedanyway and hence the default value must befalse.