我有一个UserControl,它由几个子控件组成,我们称之为MyUserControl
。
所以它包含一个textbox
作为子控件。如果我有孩子textbox
,我如何得到MyUserControl
作为父母,而不仅仅是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
我只是cast作为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));
}