ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

FindChildByName

Uses the VisualTreeHelper in a WPF application to find a child of the type FrameworkElement by its name recursively.

Source

public static FrameworkElement FindChildByName(this FrameworkElement parent, string name)
{
	FrameworkElement result = null;
	int childCount = VisualTreeHelper.GetChildrenCount(parent);
	for (int i = 0; i < childCount; i++)
	{
		var child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
		if (child != null)
		{
			if (child.Name.Equals(name))
			{
				result = child;
				break;
			}
			result = child.FindChildByName(name);
			if (result != null)
			{
				break;
			}
		}
	}
	return result;
}

Example

public partial class MyUserControl : UserControl
{
	public MyUserControl()
	{
		Loaded += MyUserControlLoaded;
		InitializeComponent();
	}

	private void  MyUserControlLoaded(object sender, RoutedEventArgs e)
	{
		var childElement = this.FindChildByName("NestedChildElement");
	}
}

Author: Matthias Glauch

Submitted on: 24 jun 2011

Language: C#

Type: System.Windows.FrameworkElement

Views: 5221