下面是我所做的:
我从UserControl继承并将检查放在已加载事件的EventHandler中。
然后我让我的控件继承我的CustomControl,这很好。
public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
string controlName = child.GetValue(Control.NameProperty) as string;
if (controlName == name)
{
return child as T;
}
else
{
T result = FindVisualChildByName<T>(child, name);
if (result != null)
{
return result;
}
}
}
return null;
}
我不喜欢这个解决方案,但它是有效的。