質問

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?

役に立ちましたか?

解決

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;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top