Skip to content

Instantly share code, notes, and snippets.

@wi7a1ian
Last active March 18, 2019 09:25
Show Gist options
  • Save wi7a1ian/81237397c0f864f8704aa5f2a82ca24b to your computer and use it in GitHub Desktop.
Save wi7a1ian/81237397c0f864f8704aa5f2a82ca24b to your computer and use it in GitHub Desktop.
Find a parent element of the requested type #wpv #csharp
public static class VisualTreeHelperExtensions
{
public static T FindAncestor<T>(DependencyObject dependencyObject)
where T : class
{
DependencyObject target = dependencyObject;
do
{
target = VisualTreeHelper.GetParent(target);
}
while (target != null && !(target is T));
return target as T;
}
public static T FindAncestor<T>(this DependencyObject obj)
where T : class
{
return FindAncestor<T>(obj);
}
}
var grid1 = this.FindAncestor<Grid>();
var grid2 = VisualTreeHelperExtensions.FindAncestor<Grid>(target);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment