如何对Windows Form单选按钮进行分组?


Answers:


425

将一个组的所有单选按钮放在a Panel或a之类的容器对象中GroupBox。这将自动在Windows窗体中将它们分组在一起。


13
@mohammadsadeghsaati问题是有关Windows窗体RadioButton的,它不公开GroupName属性。
UweB 2014年

2
@UweB如果由于任何问题而无法添加组框和面板怎么办,可以说我的表格空间不足。然后?
穆罕默德·萨奇布

2
@MuhammadSaqib这是不可能的,因为面板的大小可以为零。我的意思是带有无形边框且没有边距的面板与普通形式相同。只需使用右侧面板-TableLayoutPanel(如果您应该在表中分组等)
Alex Zhukovskiy



24

我喜欢在WPF中将RadioButtons分组的概念。有一个属性GroupName指定哪些RadioButton控件是互斥的(http://msdn.microsoft.com/de-de/library/system.windows.controls.radiobutton.aspx)。

因此,我为WinForms编写了一个支持该功能的派生类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.ComponentModel;

namespace Use.your.own
{
    public class AdvancedRadioButton : CheckBox
    {
        public enum Level { Parent, Form };

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the level that specifies which RadioButton controls are affected."),
        DefaultValue(Level.Parent)]
        public Level GroupNameLevel { get; set; }

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the name that specifies which RadioButton controls are mutually exclusive.")]
        public string GroupName { get; set; }

        protected override void OnCheckedChanged(EventArgs e)
        {
            base.OnCheckedChanged(e);

            if (Checked)
            {
                var arbControls = (dynamic)null;
                switch (GroupNameLevel)
                {
                    case Level.Parent:
                        if (this.Parent != null)
                            arbControls = GetAll(this.Parent, typeof(AdvancedRadioButton));
                        break;
                    case Level.Form:
                        Form form = this.FindForm();
                        if (form != null)
                            arbControls = GetAll(this.FindForm(), typeof(AdvancedRadioButton));
                        break;
                }
                if (arbControls != null)
                    foreach (Control control in arbControls)
                        if (control != this &&
                            (control as AdvancedRadioButton).GroupName == this.GroupName)
                            (control as AdvancedRadioButton).Checked = false;
            }
        }

        protected override void OnClick(EventArgs e)
        {
            if (!Checked)
                base.OnClick(e);
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            CheckBoxRenderer.DrawParentBackground(pevent.Graphics, pevent.ClipRectangle, this);

            RadioButtonState radioButtonState;
            if (Checked)
            {
                radioButtonState = RadioButtonState.CheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.CheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.CheckedDisabled;
            }
            else
            {
                radioButtonState = RadioButtonState.UncheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.UncheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.UncheckedDisabled;
            }

            Size glyphSize = RadioButtonRenderer.GetGlyphSize(pevent.Graphics, radioButtonState);
            Rectangle rect = pevent.ClipRectangle;
            rect.Width -= glyphSize.Width;
            rect.Location = new Point(rect.Left + glyphSize.Width, rect.Top);

            RadioButtonRenderer.DrawRadioButton(pevent.Graphics, new System.Drawing.Point(0, rect.Height / 2 - glyphSize.Height / 2), rect, this.Text, this.Font, this.Focused, radioButtonState);
        }

        private IEnumerable<Control> GetAll(Control control, Type type)
        {
            var controls = control.Controls.Cast<Control>();

            return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Concat(controls)
                                      .Where(c => c.GetType() == type);
        }
    }
}

3
在需要在TableLayoutPanel内的组中使用RadioButton的情况下,这对我很方便-谢谢!
pelazem 2014年

我正在尝试将此类用于自己的一种窗体,但无法使控件显示在组框的顶部(好像它是组框的标题)。它旨在用作顶级单选按钮(id est,此单选按钮的组是位于表单根部的面板,而组框是同级)。是否有任何示例代码说明如何使用此类来实现这一目标?
阿吉·哈默提(Agi Hammerthief)

我会写 IEnumerable<Control> arbControls = null;而不是使用动态。该var口罩甚至更多,这就是为什么我通常在我的代码只使用显式类型。否则,做得很好,非常感谢分享!+1
sɐunıɔןɐqɐp

11

不带面板的单选按钮

public class RadioButton2 : RadioButton
{
   public string GroupName { get; set; }
}

private void RadioButton2_Clicked(object sender, EventArgs e)
{
    RadioButton2 rb = (sender as RadioButton2);

    if (!rb.Checked)
    {
       foreach (var c in Controls)
       {
           if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
           {
              (c as RadioButton2).Checked = false;
           }
       }

       rb.Checked = true;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    //a group
    RadioButton2 rb1 = new RadioButton2();
    rb1.Text = "radio1";
    rb1.AutoSize = true;
    rb1.AutoCheck = false;
    rb1.Top = 50;
    rb1.Left = 50;
    rb1.GroupName = "a";
    rb1.Click += RadioButton2_Clicked;
    Controls.Add(rb1);

    RadioButton2 rb2 = new RadioButton2();
    rb2.Text = "radio2";
    rb2.AutoSize = true;
    rb2.AutoCheck = false;
    rb2.Top = 50;
    rb2.Left = 100;
    rb2.GroupName = "a";
    rb2.Click += RadioButton2_Clicked;
    Controls.Add(rb2);

    //b group
    RadioButton2 rb3 = new RadioButton2();
    rb3.Text = "radio3";
    rb3.AutoSize = true;
    rb3.AutoCheck = false;
    rb3.Top = 80;
    rb3.Left = 50;
    rb3.GroupName = "b";
    rb3.Click += RadioButton2_Clicked;
    Controls.Add(rb3);

    RadioButton2 rb4 = new RadioButton2();
    rb4.Text = "radio4";
    rb4.AutoSize = true;
    rb4.AutoCheck = false;
    rb4.Top = 80;
    rb4.Left = 100;
    rb4.GroupName = "b";
    rb4.Click += RadioButton2_Clicked;
    Controls.Add(rb4);
}


5

GroupBox更好。但不仅可以使用分组框,甚至都可以使用PanelsSystem.Windows.Forms.Panel)。

  • 这在设计Internet协议版本4设置对话框时非常有用。(使用PC(windows)进行检查,然后您可以了解其行为)

5

默认情况下,共享容器内的所有单选按钮都在同一组中。意思是,如果您选中其中之一,则其他复选框将被取消选中。如果要创建独立的单选按钮组,则必须将它们置于不同的容器中,例如Group Box,或通过后面的代码控制其“已检查”状态。


4

如果您不能将它们放入一个容器中,则必须编写代码来更改每个RadioButton的选中状态:

private void rbDataSourceFile_CheckedChanged(object sender, EventArgs e)
{
    rbDataSourceNet.Checked = !rbDataSourceFile.Checked;
}

private void rbDataSourceNet_CheckedChanged(object sender, EventArgs e)
{
  rbDataSourceFile.Checked = !rbDataSourceNet.Checked;
}

这将使您陷入无限循环,
Michael Sandler
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.