How can I find WPF controls by name or type?

后端 未结 18 2945
庸人自扰
庸人自扰 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:53

    I edited CrimsonX's code as it was not working with superclass types:

    public static T FindChild(DependencyObject depObj, string childName)
       where T : DependencyObject
    {
        // Confirm obj is valid. 
        if (depObj == null) return null;
    
        // success case
        if (depObj is T && ((FrameworkElement)depObj).Name == childName)
            return depObj as T;
    
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
    
            //DFS
            T obj = FindChild(child, childName);
    
            if (obj != null)
                return obj;
        }
    
        return null;
    }
    

提交回复
热议问题