开发者

Problem with extension method

开发者 https://www.devze.com 2023-03-31 05:38 出处:网络
I ha开发者_Go百科ve declared the following extension method: public static T FindAncestor<T>(DependencyObject obj) where T : DependencyObject

I ha开发者_Go百科ve 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消