简体   繁体   中英

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

I have dynamic added controls in my XAML UI. How I can find a specific control with a name.

There is a way to do that. You can use the VisualTreeHelper to walk through all the objects on the screen. A convenient method I use (obtained it somewhere from the web) is the FindControl method:

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

You can use it like this:

var combo = ControlHelper.FindControl<ComboBox>(this, typeof(ComboBox), "ComboBox123");

When you create the Control in XAML you can give it a x:Name="..." Tag. In your corresponding C# Class the Control will be available under that name.
Some Container Views like Grid got a Children Property, you can use this to search for Controls inside them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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