Knowing if a DependencyProperty has not been set in XAML

天涯浪子 提交于 2019-11-29 09:39:14

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/19798104/knowing-if-a-dependencyproperty-has-not-been-set-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!