有没有办法找到Style是否在ResourceDictionary中而不是手动搜索?

时间:2015-08-11 20:48:37

标签: c# wpf

我有一个ResourceDictionary有很多资源,我需要查找它是否具有特定类型的样式。

我知道您可以使用FrameworkElement方法搜索Application.CurrentFindResource,但我无法在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);
}

1 个答案:

答案 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();
}