查找包含隐藏和折叠节点的逻辑子节点

时间:2012-05-23 15:09:10

标签: wpf xaml recursion logical-tree

我已经尝试找到这个问题的答案,在每一篇文章中我都发现有一个答案可以递归地找到孩子,但是没有一个能与隐藏或折叠的孩子一起工作

同样在每个帖子中,有人问过这是否可行,但没有人回答,所以我开始认为这是不可能的

如果有人有办法这样做,我将永远感激。

我的功能如下:

        public static DependencyObject FindLogicalDescendentByName(this DependencyObject source, string name)
    {
        DependencyObject result = null;
        IEnumerable children = LogicalTreeHelper.GetChildren(source);

        foreach (var child in children)
        {
            if (child is DependencyObject)
            {
                if (child is FrameworkElement)
                {
                    if ((child as FrameworkElement).Name.Equals(name))
                        result = (DependencyObject)child;
                    else
                        result = (child as DependencyObject).FindLogicalDescendentByName(name);
                }
                else
                {
                    result = (child as DependencyObject).FindLogicalDescendentByName(name);
                }
                if (result != null)
                    return result;
            }
        }
        return result;
    }

-EDITED 所以, 我意识到我的问题是我在创建项目之前试图找到它,

我绑定到xaml中的某个属性,该属性将以某个给定的名称找到一个项目,但该项目并未在该时间点创建,如果我在xaml中重新订购该项目,则它可以正常运行被发现...... doh!

1 个答案:

答案 0 :(得分:2)

这是我的代码,如果你指定X:Name和类型

,它就有效

通话示例:

System.Windows.Controls.Image myImage = FindChild<System.Windows.Controls.Image>(this (or parent), "ImageName");



/// <summary>
/// Find specific child (name and type) from parent
/// </summary>
public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
   // Confirm parent and childName are valid. 
   if (parent == null) return null;

   T foundChild = null;

   int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
   for (int i = 0; i < childrenCount; i++)
   {
      var child = VisualTreeHelper.GetChild(parent, i);
      // If the child is not of the request child type child
      T childType = child as T;
      if (childType == null)
      {
         // recursively drill down the tree
         foundChild = FindChild<T>(child, childName);

         // If the child is found, break so we do not overwrite the found child. 
         if (foundChild != null) break;
      }
      else if (!string.IsNullOrEmpty(childName))
      {
         var frameworkElement = child as FrameworkElement;
         // If the child's name is set for search
         if (frameworkElement != null && frameworkElement.Name == childName)
         {
            // if the child's name is of the request name
            foundChild = (T)child;
            break;
         }
      }
      else
      {
         // child element found.
         foundChild = (T)child;
         break;
      }
   }

     return foundChild;
  }