In WPF we can able to get the style based on the target type, like below:
control.Style = (Style)toplevelcontrol.TryFindResource(typeof(control))
But in WinRT I can't do that. I can only use a key to get the resource. Is it possible to get the resource based on target type? Please help me to resolve this.
Thanks in advance
The main difference between WPF and Winrt for dealing with resources here is that you get FindResource()
and siblings in WPF objects, while in Winrt you just have the Resources
property.
The basic technique, where the object type is used as the key for TargetType
styles, still works though. Here's a simple helper extension method to do what you want:
public static object TryFindResource(this FrameworkElement element, object key)
{
if (element.Resources.ContainsKey(key))
{
return element.Resources[key];
}
return null;
}
Call just like you would in WPF:
control.Style = (Style)toplevelcontrol.TryFindResource(control.GetType());
(Note that your original example would not compile, as control
is a variable, and you can't use typeof
on a variable. I've fixed the bug in the above example call).
this also works so good like below,
if (element.Resources.ContainsKey(key))
return element.Resources[key];
else
{
if (element.Parent != null && element.Parent is FrameworkElement)
return ((FrameworkElement)element.Parent).TryFindResource(key);
else
{
if (Application.Current.Resources.ContainsKey(key))
return Application.Current.Resources[key];
}
}
if element dont have that key it search in its parent element
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.