I have declared the following extension method:
public static T FindAncestor<T>(DependencyObject obj) where T : DependencyObject
{
while (obj != null)
{
T o = obj as T;
if (o != null)
{
return o;
}
obj = VisualTreeHelper.GetParent(obj);
}
return null;
}
[System.Runtime.CompilerServices.Extension()]
public static T FindAncestor<T>(UIElement obj) where T : UIElement
{
return FindAncestor<T>((DependencyObject)obj);
}
It doesn't seem to work with TextBlock:
var csiPage = (sender as TextBlock).FindAncestor<NotebookPageView>();
NotebookPageView inherits from UserControl.
Why isn't the extension method available?
That's not an extension method. It's just a static method. To make it an extension method you need to use the this keyword on the parameter:
public static T FindAncestor<T>(this DependencyObject obj)
Also, as @Jonathan reminds below, extension methods need to be in a static class, so make sure that's the case in your code.
For more information see the MSDN documentation on extension methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With