查找所有子控件WPF [英] Finding ALL child controls WPF

查看:178
本文介绍了查找所有子控件WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一个WPF控件内的所有控件。我有看很多的样品,似乎他们都要么需要一个名称作为参数传递或者干脆不工作。

I would like to find all of the controls within a WPF control. I have had a look at a lot of samples and it seems that they all either require a Name to be passed as parameter or simply do not work.

我有现有的code,但它不能正常工作:

I have existing code but it isn't working properly:

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>(object parent) where T : DependencyObject
        {
            List<T> logicalCollection = new List<T>();
            GetLogicalChildCollection(parent as DependencyObject, 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这样的:

You can get child button controls in RootGrid f.e like that:

 List<Button> button = GetLogicalChildCollection<Button>(RootGrid);

这篇关于查找所有子控件WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆