通过代码检查 DataContext 是否被继承

Check if DataContext is Inherited via code

我想检查 UserControl 的 DataContext 值是从父元素继承,还是直接在当​​前 UserControl 上设置(本地值),通过 C# 代码。

我可以使用 visual studio wpf 可视化工具 找到此信息,但我不知道如何通过代码执行此操作。

我附上了包含我想要的信息的屏幕截图(黄色突出显示)。

使用 DependencyPropertyHelper:

var helper = DependencyPropertyHelper.GetValueSource(
    control,
    FrameworkElement.DataContextProperty);

Debug.WriteLine(helper.BaseValueSource);

BaseValueSource 的类型是以下枚举(来自 .NET Reference Source):

public enum BaseValueSource
{
    /// <summary> The source is not known by the Framework. </summary>
    Unknown                 = BaseValueSourceInternal.Unknown,
    /// <summary> Default value, as defined by property metadata. </summary>
    Default                 = BaseValueSourceInternal.Default,
    /// <summary> Inherited from an ancestor. </summary>
    Inherited               = BaseValueSourceInternal.Inherited,
    /// <summary> Default Style for the current theme. </summary>
    DefaultStyle            = BaseValueSourceInternal.ThemeStyle,
    /// <summary> Trigger in the default Style for the current theme. </summary>
    DefaultStyleTrigger     = BaseValueSourceInternal.ThemeStyleTrigger,
    /// <summary> Style setter. </summary>
    Style                   = BaseValueSourceInternal.Style,
    /// <summary> Trigger in the Template. </summary>
    TemplateTrigger         = BaseValueSourceInternal.TemplateTrigger,
    /// <summary> Trigger in the Style. </summary>
    StyleTrigger            = BaseValueSourceInternal.StyleTrigger,
    /// <summary> Implicit Style reference. </summary>
    ImplicitStyleReference  = BaseValueSourceInternal.ImplicitReference,
    /// <summary> Template that created the element. </summary>
    ParentTemplate          = BaseValueSourceInternal.ParentTemplate,
    /// <summary> Trigger in the Template that created the element. </summary>
    ParentTemplateTrigger   = BaseValueSourceInternal.ParentTemplateTrigger,
    /// <summary> Local value. </summary>
    Local                   = BaseValueSourceInternal.Local,
}