How can I find WPF controls by name or type?

后端 未结 18 3635
庸人自扰
庸人自扰 2020-11-21 04:23

I need to search a WPF control hierarchy for controls that match a given name or type. How can I do this?

18条回答
  •  暖寄归人
    2020-11-21 04:49

    To find an ancestor of a given type from code, you can use:

    [CanBeNull]
    public static T FindAncestor(DependencyObject d) where T : DependencyObject
    {
        while (true)
        {
            d = VisualTreeHelper.GetParent(d);
    
            if (d == null)
                return null;
    
            var t = d as T;
    
            if (t != null)
                return t;
        }
    }
    

    This implementation uses iteration instead of recursion which can be slightly faster.

    If you're using C# 7, this can be made slightly shorter:

    [CanBeNull]
    public static T FindAncestor(DependencyObject d) where T : DependencyObject
    {
        while (true)
        {
            d = VisualTreeHelper.GetParent(d);
    
            if (d == null)
                return null;
    
            if (d is T t)
                return t;
        }
    }
    

提交回复
热议问题