繁体   English   中英

如何使用C#代码在XAML UI中查找具有特定名称的控件?

[英]How to find a control with a specific name in an XAML UI with C# code?

我的XAML UI中有动态添加的控件。 如何找到具有名称的特定控件。

有办法做到这一点。 您可以使用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");

在XAML中创建Control时,可以为其指定x:Name="..."标记。 在相应的C#类中,Control将以该名称提供。
像Grid这样的一些Container视图有一个Children属性,你可以使用它来搜索它们内部的Controls。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM