0

I have a UserControl that consists of several child controls lets call it MyUserControl.

So it contains a textbox among other controls as child. If I have the child textbox, how do I get MyUserControl as the parent and not just the Grid that textbox resides in.

There's a static method that I found but it does not work.

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));

}

the line current = current.Parent; says can't convert DependencyObject to Control

PutraKg
  • 2,226
  • 3
  • 31
  • 60
  • Have you tried casting the type to control? For example `current = current.Parent as Control;` or `current = (Control) current.Parent;`. Assuming the parent of the control passed into the method can by typecasted into Control. – Keyur PATEL Aug 29 '16 at 06:08
  • I tried casting like `FrameworkElement current = control;` and `current = current.Parent as FrameworkElement;` and it works. – PutraKg Aug 29 '16 at 06:45

1 Answers1

1

I just cast as FrameworkElement and it works.

 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));
    }
PutraKg
  • 2,226
  • 3
  • 31
  • 60