获取组中选定 RadioButton 的索引组中、索引、RadioButton

2023-09-06 19:14:49 作者:微笑的嘴角╮淡淡的伤

I have got a reference to a RadioButton rb1. How can I get the index of the selected RadioButton in rb1's group ? I have googled for a while but without success.

Any help will be greatly appreciated

解决方案 vc里面的控件列表哪里有radio button 如果不在,能不能告诉我在哪里 谢谢

If you got to this point then there is probably something wrong with your design and you should reconsider it.

that being said you could traverse the visual tree and find it like this:

        /// Returns the first GroupBox ancester            
        public DependencyObject  FindAncestor(DependencyObject current)

        {
            current = VisualTreeHelper.GetParent(current);

            while (current != null)
            {
                if (current is GroupBox)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            };
            return null;
        }

then go over the children and find the checked radioButton

    public RadioButton FindChild<T>(DependencyObject parent)       
    {
        // Confirm parent and childName are valid.
        if (parent == null) return null;

        RadioButton foundChild = null;

        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            // If the child is not of the request child type child
            var childType = child as radioButton;
            if (childType == null)
            {
                // recursively drill down the tree
                foundChild = FindChild(child);

                // If the child is found, break so we do not overwrite the found child.
                if (foundChild != null) return foundChild ;
            }
            else if (childName.IsChecked == true)
            {
               return foundChild;  
            }
        }

        return null;
    }