How can I find WPF controls by name or type?

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

    You can use the VisualTreeHelper to find controls. Below is a method that uses the VisualTreeHelper to find a parent control of a specified type. You can use the VisualTreeHelper to find controls in other ways as well.

    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 FindVisualParent(DependencyObject child)
         where T : DependencyObject
       {
          // get parent item
          DependencyObject parentObject = VisualTreeHelper.GetParent(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 FindVisualParent(parentObject);
          }
       }
    }
    

    Call it like this:

    Window owner = UIHelper.FindVisualParent(myControl);
    

提交回复
热议问题