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

Cor*_*aar 5 c# uwp uwp-xaml

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

小智 10

有办法做到这一点.您可以使用它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;
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

var combo = ControlHelper.FindControl<ComboBox>(this, typeof(ComboBox), "ComboBox123");
Run Code Online (Sandbox Code Playgroud)