[英]Get the UserControl of a Child control in Windows 10
我有一个由几个子控件组成的UserControl,将其称为MyUserControl
。
因此,它在其他控件中包含一个textbox
作为子控件。 如果我有子textbox
,如何使MyUserControl
作为父textbox
,而不仅仅是textbox
所在的Grid
。
我找到了一个静态方法,但是它不起作用。
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
我只是转换为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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.