我需要在WPF控件层次结构中搜索与给定名称或类型匹配的控件。我该怎么做呢?


当前回答

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

    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)。

其他回答

如果您希望找到特定类型的ALL控件,那么您可能也会对这个代码段感兴趣

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

这里有一些我经常使用的方法。

用法:

// Starts the search from thisUiElement (might be a UserContol, Window, etc..)
var combobox = thisUiElement.ChildOfType<ComboBox>();
var employeesListBox = thisUiElement.ChildOfName("EmployeesListBox");
// Starts the search from MainWindow to find the first DataGrid
var dataGrid = WpfUtils.ChildOfType<DataGrid>();
// Starts the search from MainWindow to find the all ListViews
List<ComboBox> allListViews = WpfUtils.ChildOfType<ListView>();
// Starts the search from MainWindow to find the element of name EmployeesComboBox
var combobox = WpfUtils.ChildOfName("EmployeesComboBox");

实现:

/*
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace WpfUtilities;
*/

public static class WpfUtils{

    public static Window AppMainWindow =>
        Application.Current?.MainWindow;

    #region Find By Type
    
    // Start the search from MainWindow, example usage: var combobox = WpfUtils.ChildOfType<ComboBox>();
    public static T ChildOfType<T>() where T : DependencyObject =>
        ChildOfType<T>(AppMainWindow);
        
    /// This will return the first child of type T
    public static T ChildOfType<T>(this DependencyObject parent)
        where T : DependencyObject
    {
        if (parent == null) return null;
        T child = default;
        var numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; i < numVisuals; i++)
        {
            var v = VisualTreeHelper.GetChild(parent, i);
            child = v as T ?? v.ChildOfType<T>();
            if (child != null)
                break;
        }

        return child;
    }
    
    // Start the search from MainWindow, example usage: List<ComboBox> comboboxes = WpfUtils.ChildOfType<ComboBox>();
    public static IEnumerable<T> ChildrenOfType<T>() where T : DependencyObject =>
        ChildrenOfType<T>(AppMainWindow);
    
    /// This will not break the search when finding the first kid of type T, but it will keep searching to return all kids of type T
    public static IEnumerable<T> ChildrenOfType<T>(
        this DependencyObject parent) where T : DependencyObject
    {
        if (parent == null) yield break;
        var numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; i < numVisuals; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            if (child is T dependencyObject)
                yield return dependencyObject;

            foreach (var childOfChild in child.ChildrenOfType<T>())
                yield return childOfChild;
        }
    }
    
    #endregion  

    #region Find By Name
    
    /// If parent is null, the search will start from MainWindow, example usage: var combobox = WpfUtils.ChildOfName("EmployeesCombobox");
    public static FrameworkElement ChildOfName(string childName,
        DependencyObject parent = null)
    {
        parent ??= AppMainWindow;
        object child = null;
        var numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; i < numVisuals; i++)
        {
            var v = VisualTreeHelper.GetChild(parent, i);
            child = v is FrameworkElement f && f.Name == childName
                ? f
                : ChildOfName(childName, v);

            if (child != null)
                break;
        }

        return child as FrameworkElement;
    }
    
    #endregion
    
    #region
    
    // Yet another useful method, if you are writing code in a .xaml.cs file and you want to get the parent of a type.. example usage: this.ParentOfType<Grid>(); this.ParentOfType<UserControl>(); this.ParentOfType<Window>(); 
    public static T ParentOfType<T>(this DependencyObject child) where T : DependencyObject
    {
        var parentDepObj = child;
        do
        {
            parentDepObj = VisualTreeHelper.GetParent(parentDepObj);
            if (parentDepObj is T parent) return parent;
        } while (parentDepObj != null);

        return null;
    }
    
    #endregion
}

我可能只是在重复其他人,但我确实有一段漂亮的代码,它用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;
    }
}

希望对你有用。

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

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

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

    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)。