How can I find WPF controls by name or type?

后端 未结 18 3047
庸人自扰
庸人自扰 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条回答
  •  旧时难觅i
    2020-11-21 04:54

    Whilst I love recursion in general, it's not as efficient as iteration when programming in C#, so perhaps the following solution is neater than the one suggested by John Myczek? This searches up a hierarchy from a given control to find an ancestor control of a particular type.

    public static T FindVisualAncestorOfType(this DependencyObject Elt)
        where T : DependencyObject
    {
        for (DependencyObject parent = VisualTreeHelper.GetParent(Elt);
            parent != null; parent = VisualTreeHelper.GetParent(parent))
        {
            T result = parent as T;
            if (result != null)
                return result;
        }
        return null;
    }
    

    Call it like this to find the Window containing a control called ExampleTextBox:

    Window window = ExampleTextBox.FindVisualAncestorOfType();
    

提交回复
热议问题