Skip to content

Instantly share code, notes, and snippets.

@mii9000
Last active November 27, 2015 11:25
Show Gist options
  • Save mii9000/fc5334e6df9e18aadf61 to your computer and use it in GitHub Desktop.
Save mii9000/fc5334e6df9e18aadf61 to your computer and use it in GitHub Desktop.
Extensions method that searches up or down VisualTree from the source element
public static class WinRTXamlQuery
{
/// <summary>
/// Searches descendants recursively down to the last one
/// </summary>
/// <typeparam name="T">FrameworkElement type expected</typeparam>
/// <param name="Source">FrameworkElement searched from</param>
/// <param name="Name">Name of the control to expect</param>
public static IEnumerable<T> GetDescendents<T>(this FrameworkElement Source, string Name = "")
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(Source); i++)
{
var child = VisualTreeHelper.GetChild(Source, i);
if (child != null)
{
if (Name == "")
{
if (child.GetType() == typeof(T))
{
yield return (T)Convert.ChangeType(child, typeof(T));
}
}
else
{
FrameworkElement fc = child as FrameworkElement;
if (child.GetType() == typeof(T) && fc.Name == Name)
{
yield return (T)Convert.ChangeType(child, typeof(T));
}
}
foreach (T childOfChild in GetDescendents<T>((FrameworkElement)child, Name))
{
yield return childOfChild;
}
}
}
}
/// <summary>
/// Searches ascendants recursively up to the first one
/// </summary>
/// <typeparam name="T">FrameworkElement type expected</typeparam>
/// <param name="Source">FrameworkElement searched from</param>
/// <param name="Name">Name of the control to expect</param>
public static IEnumerable<T> GetAscendants<T>(this FrameworkElement Source, string Name = "")
{
var parent = VisualTreeHelper.GetParent(Source);
if (parent != null)
{
if (Name == "")
{
if (parent.GetType() == typeof(T))
{
yield return (T)Convert.ChangeType(parent, typeof(T));
}
}
else
{
var fc = parent as FrameworkElement;
if (parent.GetType() == typeof(T) && fc.Name == Name)
{
yield return (T)Convert.ChangeType(parent, typeof(T));
}
}
foreach (var p in GetAscendants<T>((FrameworkElement)parent))
{
yield return p;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment