当WPF控件的名称在xaml代码中设置时,是否有一种方法可以通过其名称找到其父级控件?
element = VisualTreeHelper.GetParent(element) as UIElement;
在这里,“element”指的是需要获取父元素的子元素。
实际上,我能够通过使用VisualTreeHelper递归查找父控件的名称和类型来实现此操作。
/// <summary>
/// Recursively finds the specified named parent in a control hierarchy
/// </summary>
/// <typeparam name="T">The type of the targeted Find</typeparam>
/// <param name="child">The child control to start with</param>
/// <param name="parentName">The name of the parent to find</param>
/// <returns></returns>
private static T FindParent<T>(DependencyObject child, string parentName)
where T : DependencyObject
{
if (child == null) return null;
T foundParent = null;
var currentParent = VisualTreeHelper.GetParent(child);
do
{
var frameworkElement = currentParent as FrameworkElement;
if(frameworkElement.Name == parentName && frameworkElement is T)
{
foundParent = (T) currentParent;
break;
}
currentParent = VisualTreeHelper.GetParent(currentParent);
} while (currentParent != null);
return foundParent;
}