Search code examples
c#wpfdatacontext

Check if DataContext is Inherited via code


I want to check if a DataContext value for a UserControl is inherited from parent element or if was directly set on the current UserControl (local value), via C# code.

I can find this information by using visual studio wpf visualizer tool, but I can't figure out how to do this via code.

I have attached a screenshot with the information that I want (yellow highlighted). enter image description here


Solution

  • Use DependencyPropertyHelper:

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

    The type of BaseValueSource is the following enum (from .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,
    }