除了手动搜索之外,是否有其他方法可以查找样式是否在ResourceDictionary中



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

我知道你可以用FindResource方法搜索FrameworkElementApplication.Current,但我找不到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);
}

使用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();
}

最新更新