C# 除了手动搜索外,是否有其他方法可以确定某个样式是否在ResourceDictionary中?

C# 除了手动搜索外,是否有其他方法可以确定某个样式是否在ResourceDictionary中?,c#,wpf,C#,Wpf,我有一个ResourceDictionary,里面有很多资源,我需要找出它是否有适合特定类型的样式 我知道您可以使用FindResource方法在FrameworkElement和Application.Current中搜索,但我在resourceddictionary本身中找不到方法,也找不到常规静态方法 除了手工操作之外,还有没有其他方法可以实现这一点,代码与此类似: private List<Style> stylesForType = new List<Style>

我有一个
ResourceDictionary
,里面有很多资源,我需要找出它是否有适合特定类型的样式

我知道您可以使用
FindResource
方法在
FrameworkElement
Application.Current
中搜索,但我在
resourceddictionary
本身中找不到方法,也找不到常规静态方法

除了手工操作之外,还有没有其他方法可以实现这一点,代码与此类似:

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);
}
private List stylesForType=new List();
私有void FindResourceForType(ResourceDictionary资源,类型类型)
{
foreach(资源中的var资源.Values)
{
var style=资源作为样式;
if(style!=null&&style.TargetType==type)
{
stylesForType.Add(样式);
}
}
foreach(resources.MergedDictionaries中的var resourceDictionary)
FindResourceForType(资源字典,类型);
}

使用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();
}
private Style[]FindResourceForType(资源字典资源,类型类型)
{
返回resources.MergedDictionaries.SelectMany(d=>FindResourceForType(d,type)).Union(resources.Values.OfType().Where(s=>s.TargetType==type)).ToArray();
}

你好,格伦,谢谢你指出林克。我的原始代码还做了一些事情,这就是为什么我不能使用LINQ。但是,您不需要同时检查合并词典中的样式吗?我正在寻找一种实现这一点的内置方法,但在某些情况下,使用LINQ应该是一种合理的选择。合并的字典是其他ResourceDictionary。这个方法就是处理一个。合并的字典可以包含各自的合并字典,因此需要一个递归算法来处理它们。问题很简单,“我有一个ResourceDictionary,它有很多资源,我需要找出它是否有特定类型的样式。”你说的是对的,但是ResourceDictionary,它可以在里面合并字典,我不认为我需要澄清,抱歉。如果你检查我的代码,它实际上是一个递归算法,在这里我也检查了合并字典。我以为你已经注意到了,你用你的代码指出,我只需要检查值。感谢您的澄清。您的方法不是递归的;它不叫自己。它只会下降到资源字典的一个级别。我的方法会调用自己,您可以注意到在第一个
foreach
之后,每个合并的字典都有另一个
foreach
,我调用
FindResourceForType