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