我有一个由几个子控件组成的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
答案 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));
}