我有一个ResourceDictionary
有很多资源,我需要查找它是否具有特定类型的样式。
我知道您可以使用FrameworkElement
方法搜索Application.Current
和FindResource
,但我无法在ResourceDictionary
内找到方法,或者一般的静态方法。
有没有办法实现这一目的,而不是手工完成,代码类似于:
private List<Style> stylesForType = new List<Style>();
private void FindResourceForType(ResourceDictionary resources, Type type)
{
foreach (var resource in resources.Values)
{
var style = resource as Style;
if (style != null && style.TargetType == type)
{
stylesForType.Add(style);
}
}
foreach (var resourceDictionary in resources.MergedDictionaries)
FindResourceForType(resourceDictionary, type);
}
答案 0 :(得分:1)
使用Linq
查找定位资源字典中特定类型的样式private Style[] FindResourceForType(ResourceDictionary resources, Type type)
{
return resources.MergedDictionaries.SelectMany(d => FindResourceForType(d, type)).Union(resources.Values.OfType<Style>().Where(s => s.TargetType == type)).ToArray();
}