Is there a way to find the parents of a WPF control by its name, when the name is set in the xaml code?
Actually I was able to do this by recursively looking for the Parent control by name and type using the 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;
}
Try this,
element = VisualTreeHelper.GetParent(element) as UIElement;
Where, element being the Children - Whose Parent you need to get.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With