Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knowing if a DependencyProperty has not been set in XAML

I have a control, which exposes a DP called PlacementTarget (it's bound to a child Popup FWIW).

What I want to do is if PlacementTarget is not set in XAML, then (the control will) set it to the Window the control is in. When I say 'not set' I don't mean simply 'is null' (this allows the user dev to set PlacementTarget to null, and the control won't auto set it to the Window).

I have a field called placementTargetIsSet, which I set to true in the Change event handler

public readonly static DependencyProperty PlacementTargetProperty =
    DependencyProperty.Register(
        "PlacementTarget", typeof(UIElement), typeof(MyControl),
        new PropertyMetadata(new PropertyChangedCallback(PlacementTargetChanged)));

static void PlacementTargetChanged(
    DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    MyControl ctrl = (sender as MyControl);
    ctrl.placementTargetIsSet = true;
}

public UIElement PlacementTarget
{
    get { return (UIElement)GetValue(PlacementTargetProperty); }
    set { SetValue(PlacementTargetProperty, value); }
}

However I'm finding that the changed event is happening AFTER OnApplyTemplate and the Loaded event. i.e. when OnApplyTemplate or Loaded happen, placementTargetIsSet==false, regardless of whether PlacementTarget been set or not (in XAML).

So when can I safely assume that PlacementTarget has not been set?

like image 462
Jim W says reinstate Monica Avatar asked Nov 05 '13 20:11

Jim W says reinstate Monica


1 Answers

You don't need an extra placementTargetIsSet field and hence no PropertyChangedCallback.

In order to find out if a value has been set for the PlacementTarget property, you could just call the ReadLocalValue method and test if it returns DependencyProperty.UnsetValue:

bool placementTargetIsSet =
    ReadLocalValue(PlacementTargetProperty) != DependencyProperty.UnsetValue;
like image 127
Clemens Avatar answered Sep 27 '22 20:09

Clemens