查找逻辑子节点,包括隐藏节点和折叠节点



我试图找到这个问题的答案,在每篇帖子中,我都发现有一个递归查找孩子的答案,但它们都不适用于隐藏或折叠的孩子

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

如果有人有办法做到这一点,我将永远感激不尽。

我的函数如下所示:

        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;
    }

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

我绑定到 xaml 中的一个属性,该属性会关闭并按给定名称查找项目,但该项目不是在那个时间点创建的,如果我在 xaml 中重新排序该项目,它会起作用并且找到该项目......咚!

这是我

的代码,如果您指定 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;
  }

相关内容

  • 没有找到相关文章

最新更新