在Windows 10中获取Child控件的UserControl

时间:2016-08-29 05:29:12

标签: c# user-controls windows-10 uwp dependencyobject

我有一个由几个子控件组成的UserControl,可以调用它MyUserControl

因此它包含textbox和其他控件作为子项。如果我有孩子textbox,我如何将MyUserControl作为父母,而不仅仅是Grid所居住的textbox

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

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

1 个答案:

答案 0 :(得分:1)

我只是投射为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));
    }