Find control in the visual tree

后端 未结 1 471
执笔经年
执笔经年 2020-12-11 08:15

I am trying to get my SelectedRadioButton from a DataTemplate.

Wpf Inspector showed the Visual Tree:

<script

相关标签:
1条回答
  • 2020-12-11 09:01

    The code that I used to traverse the Visual Tree did not use the ApplyTemplate() method for a FrameworkElement in the tree and therefore cildren could not be found. In my situation the following code works:

        /// <summary>
        /// Looks for a child control within a parent by name
        /// </summary>
        public static DependencyObject FindChild(DependencyObject parent, string name)
        {
            // confirm parent and name are valid.
            if (parent == null || string.IsNullOrEmpty(name)) return null;
    
            if (parent is FrameworkElement && (parent as FrameworkElement).Name == name) return parent;
    
            DependencyObject result = null;
    
            if (parent is FrameworkElement) (parent as FrameworkElement).ApplyTemplate();
    
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                result = FindChild(child, name);
                if (result != null) break;
            }
    
            return result;
        }
    
        /// <summary>
        /// Looks for a child control within a parent by type
        /// </summary>
        public static T FindChild<T>(DependencyObject parent)
            where T : DependencyObject
        {
            // confirm parent is valid.
            if (parent == null) return null;
            if (parent is T) return parent as T;
    
            DependencyObject foundChild = null;
    
            if (parent is FrameworkElement) (parent as FrameworkElement).ApplyTemplate();
    
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                foundChild = FindChild<T>(child);
                if (foundChild != null) break;
            }
    
            return foundChild as T;
        }
    

    Thanks for the comments of "dev hedgehog" for pointing that out (I missed it).
    I will not use this approach in production code, it has to be done with databinding like "HighCore" commented.

    0 讨论(0)
提交回复
热议问题