Is it possible to get resource based on target type on WinRT platform
In WPF, we can get the style based on the target type, like below:
control.Style = (Style)toplevelcontrol.TryFindResource(typeof(control))
But in WinRT, I cannot do this. I can only use the key to get the resource. Is it possible to get a resource based on the target type? Please help me to solve this problem.
Thank you in advance
source to share
The main difference between WPF and Winrt for working with resources here is that you get FindResource()
both siblings in WPF objects, while in Winrt you have a property Resources
.
The basic method, when the object type is used as a key for styles TargetType
, still works. Here's a simple helper extension method:
public static object TryFindResource(this FrameworkElement element, object key)
{
if (element.Resources.ContainsKey(key))
{
return element.Resources[key];
}
return null;
}
Called in the same way as in WPF:
control.Style = (Style)toplevelcontrol.TryFindResource(control.GetType());
(Note that your original example will not compile as it control
is a variable and you cannot use typeof
for a variable. I fixed the error in the above call example).
source to share
this also works as well as 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 the element does not have this key, which it looks for in its parent
source to share