0

私はいくつかの子コントロールで構成される UserControl を持っており、それを呼び出すことができますMyUserControl

textboxそのため、子として他のコントロールが含まれています。child がある場合、存在するだけでなく、親としてtextbox取得するにはどうすればよいですか。MyUserControlGridtextbox

私が見つけた静的メソッドがありますが、機能しません。

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

4

1 に答える 1

1

as をキャストするだけ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 に答える