4

我试图找到这个问题的答案,在每一篇文章中我都找到了递归查找孩子的答案,但他们都没有与隐藏或崩溃的孩子一起工作

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

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

我的功能如下所示:

        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 中重新订购该项目,它可以工作并找到该项目。 .. 哦!

4

1 回答 1

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;
  }
于 2012-05-23T15:21:06.033 回答