285

我需要在 WPF 控件层次结构中搜索与给定名称或类型匹配的控件。我怎样才能做到这一点?

4

20 回答 20

332

我将 John Myczek 使用的模板格式和上面的 Tri Q 算法结合起来创建了一个可以在任何父级上使用的 findChild 算法。请记住,向下递归搜索树可能是一个漫长的过程。我只是在 WPF 应用程序上对此进行了抽查,请对您可能发现的任何错误发表评论,我将更正我的代码。

WPF Snoop是查看可视化树的有用工具 - 我强烈建议在测试时使用它或使用此算法检查您的工作。

Tri Q 的算法有一个小错误。找到孩子后,如果 childrenCount > 1 并且我们再次迭代,我们可以覆盖正确找到的孩子。因此,我在if (foundChild != null) break;代码中添加了一个来处理这种情况。

/// <summary>
/// Finds a Child of a given item in the visual tree. 
/// </summary>
/// <param name="parent">A direct parent of the queried item.</param>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="childName">x:Name or Name of child. </param>
/// <returns>The first parent item that matches the submitted type parameter. 
/// If not matching item can be found, 
/// a null parent is being returned.</returns>
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;
}

像这样称呼它:

TextBox foundTextBox = 
   UIHelper.FindChild<TextBox>(Application.Current.MainWindow, "myTextBoxName");

注意Application.Current.MainWindow可以是任何父窗口。

于 2009-11-18T23:42:25.657 回答
158

您还可以使用FrameworkElement.FindName(string)按名称查找元素。

鉴于:

<UserControl ...>
    <TextBlock x:Name="myTextBlock" />
</UserControl>

在代码隐藏文件中,您可以编写:

var myTextBlock = (TextBlock)this.FindName("myTextBlock");

当然,因为它是使用 x:Name 定义的,所以您可以只引用生成的字段,但也许您希望动态而不是静态地查找它。

这种方法也可用于模板,其中命名项目出现多次(每次使用模板一次)。

于 2009-09-25T12:48:51.857 回答
70

您可以使用VisualTreeHelper来查找控件。下面是使用 VisualTreeHelper 查找指定类型的父控件的方法。您也可以使用 VisualTreeHelper 以其他方式查找控件。

public static class UIHelper
{
   /// <summary>
   /// Finds a parent of a given item on the visual tree.
   /// </summary>
   /// <typeparam name="T">The type of the queried item.</typeparam>
   /// <param name="child">A direct or indirect child of the queried item.</param>
   /// <returns>The first parent item that matches the submitted type parameter. 
   /// If not matching item can be found, a null reference is being returned.</returns>
   public static T FindVisualParent<T>(DependencyObject child)
     where T : DependencyObject
   {
      // get parent item
      DependencyObject parentObject = VisualTreeHelper.GetParent(child);

      // we’ve reached the end of the tree
      if (parentObject == null) return null;

      // check if the parent matches the type we’re looking for
      T parent = parentObject as T;
      if (parent != null)
      {
         return parent;
      }
      else
      {
         // use recursion to proceed with next level
         return FindVisualParent<T>(parentObject);
      }
   }
}

像这样称呼它:

Window owner = UIHelper.FindVisualParent<Window>(myControl);
于 2009-03-11T21:28:37.663 回答
22

我可能只是在重复其他人,但我确实有一段漂亮的代码,它使用 FindChild() 方法扩展 DependencyObject 类,该方法将通过类型和名称为您获取孩子。只需包含并使用。

public static class UIChildFinder
{
    public static DependencyObject FindChild(this DependencyObject reference, string childName, Type childType)
    {
        DependencyObject foundChild = null;
        if (reference != null)
        {
            int childrenCount = VisualTreeHelper.GetChildrenCount(reference);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(reference, i);
                // If the child is not of the request child type child
                if (child.GetType() != childType)
                {
                    // recursively drill down the tree
                    foundChild = FindChild(child, childName, childType);
                    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 = child;
                        break;
                    }
                }
                else
                {
                    // child element found.
                    foundChild = child;
                    break;
                }
            }
        }
        return foundChild;
    }
}

希望你觉得它有用。

于 2009-10-01T00:52:54.687 回答
19

如果您想查找特定类型的所有控件,您可能也对此片段感兴趣

    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) 
        where T : DependencyObject
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);

            var childType = child as T;
            if (childType != null)
            {
                yield return (T)child;
            }

            foreach (var other in FindVisualChildren<T>(child))
            {
                yield return other;
            }
        }
    }
于 2012-02-10T14:23:23.087 回答
18

我对代码的扩展。

  • 添加重载以按类型、按类型和条件(谓词)查找一个子项,查找符合条件的所有类型的子项
  • FindChildren 方法除了是 DependencyObject 的扩展方法外,还是一个迭代器
  • FindChildren 也会遍历逻辑子树。请参阅博客文章中链接的 Josh Smith 的文章。

来源: https ://code.google.com/p/gishu-util/source/browse/#git%2FWPF%2FUtilities

解释性博客文章: http: //madcoderspeak.blogspot.com/2010/04/wpf-find-child-control-of-specific-type.html

于 2010-04-20T08:10:18.370 回答
16

这将消除一些元素 - 您应该像这样扩展它以支持更广泛的控件。对于一个简短的讨论,看看这里

 /// <summary>
 /// Helper methods for UI-related tasks.
 /// </summary>
 public static class UIHelper
 {
   /// <summary>
   /// Finds a parent of a given item on the visual tree.
   /// </summary>
   /// <typeparam name="T">The type of the queried item.</typeparam>
   /// <param name="child">A direct or indirect child of the
   /// queried item.</param>
   /// <returns>The first parent item that matches the submitted
   /// type parameter. If not matching item can be found, a null
   /// reference is being returned.</returns>
   public static T TryFindParent<T>(DependencyObject child)
     where T : DependencyObject
   {
     //get parent item
     DependencyObject parentObject = GetParentObject(child);

     //we've reached the end of the tree
     if (parentObject == null) return null;

     //check if the parent matches the type we're looking for
     T parent = parentObject as T;
     if (parent != null)
     {
       return parent;
     }
     else
     {
       //use recursion to proceed with next level
       return TryFindParent<T>(parentObject);
     }
   }

   /// <summary>
   /// This method is an alternative to WPF's
   /// <see cref="VisualTreeHelper.GetParent"/> method, which also
   /// supports content elements. Do note, that for content element,
   /// this method falls back to the logical tree of the element!
   /// </summary>
   /// <param name="child">The item to be processed.</param>
   /// <returns>The submitted item's parent, if available. Otherwise
   /// null.</returns>
   public static DependencyObject GetParentObject(DependencyObject child)
   {
     if (child == null) return null;
     ContentElement contentElement = child as ContentElement;

     if (contentElement != null)
     {
       DependencyObject parent = ContentOperations.GetParent(contentElement);
       if (parent != null) return parent;

       FrameworkContentElement fce = contentElement as FrameworkContentElement;
       return fce != null ? fce.Parent : null;
     }

     //if it's not a ContentElement, rely on VisualTreeHelper
     return VisualTreeHelper.GetParent(child);
   }
}
于 2009-06-25T09:40:10.950 回答
16

我编辑了 CrimsonX 的代码,因为它不适用于超类类型:

public static T FindChild<T>(DependencyObject depObj, string childName)
   where T : DependencyObject
{
    // Confirm obj is valid. 
    if (depObj == null) return null;

    // success case
    if (depObj is T && ((FrameworkElement)depObj).Name == childName)
        return depObj as T;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

        //DFS
        T obj = FindChild<T>(child, childName);

        if (obj != null)
            return obj;
    }

    return null;
}
于 2010-06-10T13:57:32.390 回答
14

虽然我总体上喜欢递归,但在 C# 中编程时它不如迭代高效,所以也许以下解决方案比 John Myczek 建议的解决方案更简洁?这会从给定控件向上搜索层次结构,以找到特定类型的祖先控件。

public static T FindVisualAncestorOfType<T>(this DependencyObject Elt)
    where T : DependencyObject
{
    for (DependencyObject parent = VisualTreeHelper.GetParent(Elt);
        parent != null; parent = VisualTreeHelper.GetParent(parent))
    {
        T result = parent as T;
        if (result != null)
            return result;
    }
    return null;
}

像这样调用它以找到Window包含一个名为的控件ExampleTextBox

Window window = ExampleTextBox.FindVisualAncestorOfType<Window>();
于 2011-09-06T12:31:17.443 回答
9

这是我的代码,用于按类型查找控件,同时控制我们进入层次结构的深度(maxDepth == 0 表示无限深)。

public static class FrameworkElementExtension
{
    public static object[] FindControls(
        this FrameworkElement f, Type childType, int maxDepth)
    {
        return RecursiveFindControls(f, childType, 1, maxDepth);
    }

    private static object[] RecursiveFindControls(
        object o, Type childType, int depth, int maxDepth = 0)
    {
        List<object> list = new List<object>();
        var attrs = o.GetType()
            .GetCustomAttributes(typeof(ContentPropertyAttribute), true);
        if (attrs != null && attrs.Length > 0)
        {
            string childrenProperty = (attrs[0] as ContentPropertyAttribute).Name;
            foreach (var c in (IEnumerable)o.GetType()
                .GetProperty(childrenProperty).GetValue(o, null))
            {
                if (c.GetType().FullName == childType.FullName)
                    list.Add(c);
                if (maxDepth == 0 || depth < maxDepth)
                    list.AddRange(RecursiveFindControls(
                        c, childType, depth + 1, maxDepth));
            }
        }
        return list.ToArray();
    }
}
于 2010-10-20T10:17:24.867 回答
9

exciton80 ...我遇到了您的代码没有通过用户控件递归的问题。它击中了 Grid 根并引发了错误。我相信这为我解决了这个问题:

public static object[] FindControls(this FrameworkElement f, Type childType, int maxDepth)
{
    return RecursiveFindControls(f, childType, 1, maxDepth);
}

private static object[] RecursiveFindControls(object o, Type childType, int depth, int maxDepth = 0)
{
    List<object> list = new List<object>();
    var attrs = o.GetType().GetCustomAttributes(typeof(ContentPropertyAttribute), true);
    if (attrs != null && attrs.Length > 0)
    {
        string childrenProperty = (attrs[0] as ContentPropertyAttribute).Name;
        if (String.Equals(childrenProperty, "Content") || String.Equals(childrenProperty, "Children"))
        {
            var collection = o.GetType().GetProperty(childrenProperty).GetValue(o, null);
            if (collection is System.Windows.Controls.UIElementCollection) // snelson 6/6/11
            {
                foreach (var c in (IEnumerable)collection)
                {
                    if (c.GetType().FullName == childType.FullName)
                        list.Add(c);
                    if (maxDepth == 0 || depth < maxDepth)
                        list.AddRange(RecursiveFindControls(
                            c, childType, depth + 1, maxDepth));
                }
            }
            else if (collection != null && collection.GetType().BaseType.Name == "Panel") // snelson 6/6/11; added because was skipping control (e.g., System.Windows.Controls.Grid)
            {
                if (maxDepth == 0 || depth < maxDepth)
                    list.AddRange(RecursiveFindControls(
                        collection, childType, depth + 1, maxDepth));
            }
        }
    }
    return list.ToArray();
}
于 2011-06-06T23:26:57.030 回答
8

我有一个这样的序列函数(这是完全通用的):

    public static IEnumerable<T> SelectAllRecursively<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> func)
    {
        return (items ?? Enumerable.Empty<T>()).SelectMany(o => new[] { o }.Concat(SelectAllRecursively(func(o), func)));
    }

获得直系子女:

    public static IEnumerable<DependencyObject> FindChildren(this DependencyObject obj)
    {
        return Enumerable.Range(0, VisualTreeHelper.GetChildrenCount(obj))
            .Select(i => VisualTreeHelper.GetChild(obj, i));
    }

查找层次结构树下的所有孩子:

    public static IEnumerable<DependencyObject> FindAllChildren(this DependencyObject obj)
    {
        return obj.FindChildren().SelectAllRecursively(o => o.FindChildren());
    }

您可以在 Window 上调用它来获取所有控件。

有了集合之后,就可以使用LINQ(即OfType,Where)了。

于 2014-08-20T15:45:01.940 回答
6

由于这个问题很笼统,它可能会吸引人们寻找非常琐碎案例的答案:如果您只想要一个孩子而不是后代,您可以使用 Linq:

private void ItemsControlItem_Loaded(object sender, RoutedEventArgs e)
{
    if (SomeCondition())
    {
        var children = (sender as Panel).Children;
        var child = (from Control child in children
                 where child.Name == "NameTextBox"
                 select child).First();
        child.Focus();
    }
}

或者当然是明显的 for 循环遍历儿童。

于 2011-03-06T13:03:18.413 回答
4

这些选项已经讨论了在 C# 中遍历可视化树。也可以使用 RelativeSource 标记扩展来遍历 xaml 中的可视化树。微软

按类型查找

Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type <TypeToFind>}}}" 
于 2015-04-02T15:04:21.537 回答
2

这是一个使用灵活谓词的解决方案:

public static DependencyObject FindChild(DependencyObject parent, Func<DependencyObject, bool> predicate)
{
    if (parent == null) return null;

    int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childrenCount; i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);

        if (predicate(child))
        {
            return child;
        }
        else
        {
            var foundChild = FindChild(child, predicate);
            if (foundChild != null)
                return foundChild;
        }
    }

    return null;
}

例如,您可以这样称呼它:

var child = FindChild(parent, child =>
{
    var textBlock = child as TextBlock;
    if (textBlock != null && textBlock.Name == "MyTextBlock")
        return true;
    else
        return false;
}) as TextBlock;
于 2015-09-09T15:54:59.930 回答
1

我无法使用 @CrimsonX 或 @Drew Noakes 方法找到我的控件,因为我的 ControlTemplate 位于单独的 XAML 文件中。我使用以下方法找到了控件:

private Image backImage;
private void Diagram_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
    // here is the example of the ControlTemplate declaration
    //<ControlTemplate x:Key="DiagramControlTemplate1" TargetType="{x:Type Diagram}">
    var ctrlTemplate = (ControlTemplate)FindResource("DiagramControlTemplate1");
    // diagram is the x:Name of TemplatedControl and, "backImage" is the name of control that I want to find.
    var imageControl = ctrlTemplate.FindName("backImage", diagram);
    if (imageControl != null)
    {
        this.backImage = (Image)imageControl;
    }
}

这对我有用。

于 2021-03-15T02:05:41.223 回答
0

要从代码中查找给定类型的祖先,您可以使用:

[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
    while (true)
    {
        d = VisualTreeHelper.GetParent(d);

        if (d == null)
            return null;

        var t = d as T;

        if (t != null)
            return t;
    }
}

此实现使用迭代而不是递归,这可能会稍微快一些。

如果您使用的是 C# 7,则可以稍微缩短一点:

[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
    while (true)
    {
        d = VisualTreeHelper.GetParent(d);

        if (d == null)
            return null;

        if (d is T t)
            return t;
    }
}
于 2017-03-07T12:54:57.223 回答
0

这段代码只是修复了@CrimsonX 答案的错误:

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

 // 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
        {
          // child element found.
          foundChild = (T)child;
          break;
        }
      }

      return foundChild;
    }  

如果类型匹配但名称不匹配,您只需要继续递归调用该方法(当您传递FrameworkElementas时会发生这种情况T)。否则它会返回null,这是错误的。

于 2017-11-21T21:17:55.353 回答
-2

我能够使用下面的代码按名称查找对象。

stkMultiChildControl = stkMulti.FindChild<StackPanel>("stkMultiControl_" + couter.ToString());

于 2020-12-26T20:56:11.083 回答
-8

试试这个

<TextBlock x:Name="txtblock" FontSize="24" >Hai Welcom to this page
</TextBlock>

代码背后

var txtblock = sender as Textblock;
txtblock.Foreground = "Red"
于 2015-03-23T05:57:03.007 回答