本文介绍了知道是否尚未在XAML中设置DependencyProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控件,它公开了一个称为PlacementTarget的DP(绑定到一个子弹出窗口FWIW)。

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

我想做的是,如果未在XAML中设置PlacementTarget,则(该控件将)将其设置为该控件所在的Window。当我说'not设置,我并不是说简单地是为空(这允许用户开发人员将PlacementTarget设置为null,并且控件不会将其自动设置为Window)。

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).

我有一个名为placementTargetIsSet的字段,我在Change事件处理程序中将其设置为true

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); }
}

但是我发现更改的事件在OnApplyTemplate和加载的事件。例如,当发生OnApplyTemplate或Loaded时,无论是否已设置PlacementTarget(在XAML中),placementTargetIsSet == false。

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).

因此,我何时可以安全地假定PlacementTarget尚未

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

推荐答案

您不需要额外的 placementTargetIsSet 字段因此没有PropertyChangedCallback。

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

为了找出是否已为 PlacementTarget 属性设置了一个值,您可以可以只调用方法,并测试它是否返回:

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;

这篇关于知道是否尚未在XAML中设置DependencyProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:47