如何使用C#代码在XAML界面中按名称查找控件?

9

我在XAML UI中添加了动态控件。 如何通过名称查找特定控件。

4个回答

16

有一种方法可以实现这个功能。您可以使用VisualTreeHelper遍历屏幕上的所有对象。我使用的一个方便的方法(从网上获取)是FindControl方法:

public static T FindControl<T>(UIElement parent, Type targetType, string ControlName) where T : FrameworkElement
{

    if (parent == null) return null;

    if (parent.GetType() == targetType && ((T)parent).Name == ControlName)
    {
        return (T)parent;
    }
    T result = null;
    int count = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < count; i++)
    {
        UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);

        if (FindControl<T>(child, targetType, ControlName) != null)
        {
            result = FindControl<T>(child, targetType, ControlName);
            break;
        }
    }
    return result;
}

您可以像这样使用它:
var combo = ControlHelper.FindControl<ComboBox>(this, typeof(ComboBox), "ComboBox123");

FindName 也能用吗? - Bill Hoag
谢谢,Martin!对于需要从代码访问任何“DataTemplate控件”的人,只需使用“Tag”来保持动态创建的名称,并修改上面的代码以检查控件的“Tag”属性。 - NoWar

4

我已经扩展了@Martin Tirion的版本,使其更加舒适:

  • 消除类型参数
  • 创建UIElement扩展以实现更好的使用

以下是更改后的代码:

namespace StackOwerflow.Sample.Helpers
{
    public static class UIElementExtensions
    {
        public static T FindControl<T>( this UIElement parent, string ControlName ) where T : FrameworkElement
        {
            if( parent == null )
                return null;

            if( parent.GetType() == typeof(T) && (( T )parent).Name == ControlName )
            {
                return ( T )parent;
            }
            T result = null;
            int count = VisualTreeHelper.GetChildrenCount( parent );
            for( int i = 0; i < count; i++ )
            {
                UIElement child = ( UIElement )VisualTreeHelper.GetChild( parent, i );

                if( FindControl<T>( child, ControlName ) != null )
                {
                    result = FindControl<T>( child, ControlName );
                    break;
                }
            }
            return result;
        }
    }
}

修改后,我可以这样使用:
var combo = parent.FindControl<ComboBox>("ComboBox123");

当父窗口是当前对话框时,它就像这样:

var combo = FindControl<ComboBox>("ComboBox123");

感谢 @Martin Tirion 再次帮忙!

1

当您在XAML中创建控件时,可以为其指定x:Name="..."标记。在相应的C#类中,该控件将以该名称可用。
一些容器视图(如Grid)具有Children属性,您可以使用它来搜索其中的控件。


这是答案。 - Herve Mutombo

0

我喜欢之前的答案,但我想要一些控制权,以便它可以遍历树并允许它找不到控件。

用法:

/// <summary>
/// Finds a grid panel with the name "GridVariables" and toggles it's visibility to and from visible
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public sealed partial class MainPage : Page
{
    private void btnShowVariables_Click(object sender, RoutedEventArgs e)
    {
        if (this.TryFindChildControl<Grid>("gridVariables", out var grid))
        {
            grid.Visibility = grid.Visibility.HasFlag(Visibility.Collapsed) ? Visibility.Visible : Visibility.Collapsed;
        }
    }
}

扩展类:

public static class UIElementExtensions
{
    /// <summary>
    /// Returns the first FrameworkElement with the type and name
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sourceControl"></param>
    /// <param name="name"></param>
    /// <param name="control"></param>
    /// <returns></returns>
    public static bool TryFindChildControl<T>(this UIElement sourceControl, string name, out T control, bool recursiveSearch = true)
        where T : FrameworkElement
    {
        var childCount = VisualTreeHelper.GetChildrenCount(sourceControl);
        
        for (var c = 0; c < childCount; c++)
        {
            var child = VisualTreeHelper.GetChild(sourceControl, c) as FrameworkElement;

            if (child == null) continue;

            var castChild = child as T;
            var found = castChild != null && castChild.Name.ToLower() == name.ToLower();

            if (!found)
            {
                if (recursiveSearch && TryFindChildControl<T>(child, name, out var innerChild, recursiveSearch))
                {
                    castChild = innerChild;
                }
                else
                {
                    continue;
                }
            }

            control = castChild;
            return true;
        }

        control = null;
        return false;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接