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.
WPF样式查找机制解析
本文探讨了WPF中DefaultStyleKey属性的作用及其在样式查找中的应用。通过反射获取DefaultStyleKey属性值,并展示了如何利用该属性为控件查找对应的主题样式。
1796

被折叠的 条评论
为什么被折叠?



