Last active
March 18, 2019 09:25
-
-
Save wi7a1ian/81237397c0f864f8704aa5f2a82ca24b to your computer and use it in GitHub Desktop.
Find a parent element of the requested type #wpv #csharp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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