[英]Is it possible to get resource based on target type in WinRT platform
在WPF中,我们可以根据目标类型获取样式,如下所示:
control.Style = (Style)toplevelcontrol.TryFindResource(typeof(control))
但是在WinRT中,我无法做到这一点。 我只能使用密钥来获取资源。 是否有可能根据目标类型获取资源? 请帮我解决这个问题。
提前致谢
WPF和Winrt在这里处理资源的主要区别在于你在WPF对象中获得FindResource()
和兄弟,而在Winrt中你只有Resources
属性。
将对象类型用作TargetType
样式的键的基本技术仍然有效。 这是一个简单的帮助扩展方法,可以执行您想要的操作:
public static object TryFindResource(this FrameworkElement element, object key)
{
if (element.Resources.ContainsKey(key))
{
return element.Resources[key];
}
return null;
}
像在WPF中那样打电话:
control.Style = (Style)toplevelcontrol.TryFindResource(control.GetType());
(请注意,您的原始示例不会编译,因为control
是变量,并且您不能对变量使用typeof
。我已修复上述示例调用中的错误)。
这也很好,如下所示,
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];
}
}
如果元素没有该键,则在其父元素中搜索
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.