Skip to content

Instantly share code, notes, and snippets.

@iambacon
Created August 24, 2015 15:36
Show Gist options
  • Save iambacon/6189242ef30a85fb8627 to your computer and use it in GitHub Desktop.
Save iambacon/6189242ef30a85fb8627 to your computer and use it in GitHub Desktop.
/// <summary>
/// Extension methods for <see cref="DependencyObject"/>.
/// </summary>
public static class DependancyObjectExtensions
{
/// <summary>
/// Gets the visual parent of the specified type of the child.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="child">The child.</param>
/// <returns>The parent with the specified type.</returns>
public static T GetVisualParent<T>(this DependencyObject child) where T : DependencyObject
{
while (true)
{
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
if (parentObject == null)
{
return null;
}
if (parentObject is T)
{
return parentObject as T;
}
child = parentObject;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment