Skip to content

Instantly share code, notes, and snippets.

@tmyt
Created November 22, 2015 11:18
Show Gist options
  • Save tmyt/79d53154f637fdbd029b to your computer and use it in GitHub Desktop.
Save tmyt/79d53154f637fdbd029b to your computer and use it in GitHub Desktop.
public static T FindElement<T>(this DependencyObject rootElement, string name = null)
where T : DependencyObject
{
var q = new Queue<DependencyObject>();
q.Enqueue(rootElement);
while (q.Count != 0)
{
var e = q.Dequeue();
if (e is T && (name == null || !(e is FrameworkElement) || (e as FrameworkElement).Name == name)) return e as T;
if (e == null) continue;
var c = VisualTreeHelper.GetChildrenCount(e);
for (var i = 0; i < c; ++i)
{
q.Enqueue(VisualTreeHelper.GetChild(e, i));
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment