【问题标题】:Is it possible to get resource based on target type in WinRT platformWinRT平台是否可以根据目标类型获取资源
【发布时间】:2015-06-19 15:15:04
【问题描述】:
在 WPF 中,我们可以根据目标类型获取样式,如下所示:
control.Style = (Style)toplevelcontrol.TryFindResource(typeof(control))
但在 WinRT 中我不能这样做。我只能使用密钥来获取资源。是否可以根据目标类型获取资源?
请帮我解决这个问题。
提前致谢
【问题讨论】:
标签:
c#
xaml
windows-runtime
winrt-xaml
winrt-component
【解决方案1】:
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。我已经修复了上述示例调用中的错误)。
【解决方案2】:
这也很好用,如下所示,
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];
}
}
如果元素没有该键,它将在其父元素中搜索