`

wpf - Default(Theme) style and its DefaultStyleKey

    博客分类:
  • WPF
wpf 
阅读更多

As dicsused in the subsection of Default (theme) style from the topic of Dependency Property Value Precedence we know that the theme style use the type as the key for controls; But when theme is applied to a given Element instanfe, themes lookup for the particule type is performed by checking the DefaultStyleKey;

from DefaultStyleKey, we know that it is a protected internal property, out of curious we want to find out what is the value of the DefaultStyleKey;

 

Below is the code that I used for the look up .

 

 

To reflection get a property

 

 

    public static object ReflectionGetProperty(object obj, Type type , string propertyName, BindingFlags[] bindingFlags)
    {
      if (string.IsNullOrEmpty(propertyName)) throw new ArgumentException("propertyName");
      if (bindingFlags == null) throw new ArgumentNullException("bindingFlags");
      if (type == null) throw new ArgumentNullException("type");
      if (bindingFlags.Length == 0) throw new ArgumentException("bindingFlags");


      var binding = bindingFlags[0];
      for (int i = 0; i < bindingFlags.Length; i++)
      {
        binding |= bindingFlags[i];
      }
      var prop = type.GetProperty(propertyName, binding);
      if (prop != null)
      {
        return prop.GetValue(obj, null);
      }
      return null;
    }

 

To use the ReflectionGetProperty method to get the Value of "DefaultStyleKey" 

 

 

    public static object ReflectionGetDefaultStyle(FrameworkElement frameworkElement)
    {
      if (frameworkElement == null) throw new ArgumentNullException("frameworkElement");
      object defaultStyleKey = ReflectionGetProperty(frameworkElement, typeof(FrameworkElement), "DefaultStyleKey", new BindingFlags[] { BindingFlags.NonPublic | BindingFlags.Instance });
      if (defaultStyleKey != null)
      {
        var style = frameworkElement.TryFindResource(defaultStyleKey);
        return style;
      }
      return null;
    }

 

 

and suppose visual is an FrameworkElement, this is how you get Default Style.

 

 

FrameworkElement visual = ...
var style = ReflectionGetDefaultStyle(visual);

 

If you inspect the value of DefaultStyleKey in the method, you will see that the value of the DefautlstyleKey as in the method ReflectionGetDefaultKey is 

 

 

? defaultStyleKey
{Name = "TextBlock" FullName = "System.Windows.Controls.TextBlock"}
    base {System.Type}: {Name = "TextBlock" FullName = "System.Windows.Controls.TextBlock"}
    Assembly: {PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35}
...
 

As you can see that it is just the Type of textBlock (our Visual is a TextBlock);

 

 

It does not have some pratical siginificance, but some explore that is interesting. 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics