Is it possible to get resource based on target type in WinRT platform

394 views Asked by At

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

2

There are 2 answers

0
SharpGobi On

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

0
Peter Duniho On

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).