How can I find WPF controls by name or type?

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

    This will dismiss some elements - you should extend it like this in order to support a wider array of controls. For a brief discussion, have a look here

     /// 
     /// Helper methods for UI-related tasks.
     /// 
     public static class UIHelper
     {
       /// 
       /// Finds a parent of a given item on the visual tree.
       /// 
       /// The type of the queried item.
       /// A direct or indirect child of the
       /// queried item.
       /// The first parent item that matches the submitted
       /// type parameter. If not matching item can be found, a null
       /// reference is being returned.
       public static T TryFindParent(DependencyObject child)
         where T : DependencyObject
       {
         //get parent item
         DependencyObject parentObject = GetParentObject(child);
    
         //we've reached the end of the tree
         if (parentObject == null) return null;
    
         //check if the parent matches the type we're looking for
         T parent = parentObject as T;
         if (parent != null)
         {
           return parent;
         }
         else
         {
           //use recursion to proceed with next level
           return TryFindParent(parentObject);
         }
       }
    
       /// 
       /// This method is an alternative to WPF's
       ///  method, which also
       /// supports content elements. Do note, that for content element,
       /// this method falls back to the logical tree of the element!
       /// 
       /// The item to be processed.
       /// The submitted item's parent, if available. Otherwise
       /// null.
       public static DependencyObject GetParentObject(DependencyObject child)
       {
         if (child == null) return null;
         ContentElement contentElement = child as ContentElement;
    
         if (contentElement != null)
         {
           DependencyObject parent = ContentOperations.GetParent(contentElement);
           if (parent != null) return parent;
    
           FrameworkContentElement fce = contentElement as FrameworkContentElement;
           return fce != null ? fce.Parent : null;
         }
    
         //if it's not a ContentElement, rely on VisualTreeHelper
         return VisualTreeHelper.GetParent(child);
       }
    }
    

提交回复
热议问题