开发者

WPF + Controls.UserControl. How to find a control inside?

开发者 https://www.devze.com 2023-03-16 21:00 出处:网络
In my WPF project, I have a System.Windows.Controls.UserControl control. How to find a 开发者_Go百科control inside that contol ?use VisualTree, if I understoodyour question correctly.

In my WPF project, I have a System.Windows.Controls.UserControl control. How to find a 开发者_Go百科control inside that contol ?


use VisualTree, if I understood your question correctly.

refer to msdn : http://msdn.microsoft.com/en-us/library/dd409789.aspx


In that case you would probably want to walk the visual tree, like this extension method does:

internal static T FindVisualChild<T>(this DependencyObject parent) where T : DependencyObject
{
    if (parent == null)
    {
        return null;
    }

    DependencyObject parentObject = parent;
    int childCount = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childCount; i++)
    {
        DependencyObject childObject = VisualTreeHelper.GetChild(parentObject, i);
        if (childObject == null)
        {
            continue;
        }

        var child = childObject as T;
        return child ?? FindVisualChild<T>(childObject);
    }

    return null;
}

It requires that you know the type of the control you are looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号