在Windows 10中获取子控件的UserControl

本文关键字:控件 UserControl 获取 Windows | 更新日期: 2023-09-27 18:04:23

我有一个UserControl,它由几个子控件组成,我们称之为MyUserControl

所以它包含一个textbox作为子控件。如果我有孩子textbox,我如何得到MyUserControl作为父母,而不仅仅是textbox驻留的Grid

我发现了一个静态方法,但是它不起作用。

public static T GetParentOfType<T>(this Control control)
{
    const int loopLimit = 100; // could have outside method
    var current = control;
    var i = 0;
do
{
    current = current.Parent;
    if (current == null) throw new Exception("Could not find parent of specified type");
    if (i++ > loopLimit) throw new Exception("Exceeded loop limit");
} while (current.GetType() != typeof(T));
return (T)Convert.ChangeType(current, typeof(T));

}

current = current.Parent;表示不能将DependencyObject转换为Control

在Windows 10中获取子控件的UserControl

我只是cast作为FrameworkElement,它的工作。

 public static T GetParentOfType<T>(this FrameworkElement control)
    {
        const int loopLimit = 3; // could have outside method
        FrameworkElement current = control;
        var i = 0;
        do
        {
            current = current.Parent as FrameworkElement;
            if (current == null) throw new Exception("Could not find parent of specified type");
            if (i++ > loopLimit) throw new Exception("Exceeded loop limit");
        } while (current.GetType() != typeof(T));
        return (T)Convert.ChangeType(current, typeof(T));
    }