如何使用C#代码在XAML UI中找到具有特定名称的控件? [英] How to find a control with a specific name in an XAML UI with C# code?

查看:44
本文介绍了如何使用C#代码在XAML UI中找到具有特定名称的控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

有一种方法可以做到这一点.您可以使用 VisualTreeHelper 遍历屏幕上的所有对象.我使用的一种便捷方法(可从Web上获得)是 FindControl 方法:

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

您可以像这样使用它:

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

这篇关于如何使用C#代码在XAML UI中找到具有特定名称的控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆