0

我有一个由几个子控件组成的 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;表示无法转换DependencyObjectControl

4

1 回答 1

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));
    }
于 2016-08-29T06:47:01.690 回答