简体   繁体   English

是否有可能在WinRT平台中根据目标类型获取资源

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

In WPF we can able to get the style based on the target type, like below: 在WPF中,我们可以根据目标类型获取样式,如下所示:

control.Style = (Style)toplevelcontrol.TryFindResource(typeof(control))

But in WinRT I can't do that. 但是在WinRT中,我无法做到这一点。 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. WPF和Winrt在这里处理资源的主要区别在于你在WPF对象中获得FindResource()和兄弟,而在Winrt中你只有Resources属性。

The basic technique, where the object type is used as the key for TargetType styles, still works though. 将对象类型用作TargetType样式的键的基本技术仍然有效。 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: 像在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). (请注意,您的原始示例不会编译,因为control是变量,并且您不能对变量使用typeof 。我已修复上述示例调用中的错误)。

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 如果元素没有该键,则在其父元素中搜索

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM