查找所有子控件WPF

2024-03-10

我想找到 WPF 控件中的所有控件。我查看了很多示例,似乎它们都需要名称作为参数传递,或者根本不起作用。

我有现有的代码,但它无法正常工作:

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
  if (depObj != null)
  {
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
      DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
      if (child != null && child is T)
      {
        yield return (T)child;
      }

      foreach (T childOfChild in FindVisualChildren<T>(child))
      {
        yield return childOfChild;
      }
    }
  }
}

例如,它不会得到DataGrid在一个TabItem.

有什么建议么?


你可以使用这些。

 public static List<T> GetLogicalChildCollection<T>(this DependencyObject parent) where T : DependencyObject
        {
            List<T> logicalCollection = new List<T>();
            GetLogicalChildCollection(parent, logicalCollection);
            return logicalCollection;
        }

 private static void GetLogicalChildCollection<T>(DependencyObject parent, List<T> logicalCollection) where T : DependencyObject
        {
            IEnumerable children = LogicalTreeHelper.GetChildren(parent);
            foreach (object child in children)
            {
                if (child is DependencyObject)
                {
                    DependencyObject depChild = child as DependencyObject;
                    if (child is T)
                    {
                        logicalCollection.Add(child as T);
                    }
                    GetLogicalChildCollection(depChild, logicalCollection);
                }
            }
        }

您可以在 RootGrid f.e 中获取子按钮控件,如下所示:

 List<Button> button = RootGrid.GetLogicalChildCollection<Button>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

查找所有子控件WPF 的相关文章

随机推荐