是否有多种方法可以在Windows窗体中对单选按钮进行分组?
我的表单中有几个单选按钮应该全部连接,但是我希望其中一个单独的容器在一个单独的容器中将其与其他一些相关的输入分组。 这是一般的看:
有没有办法将第四个单选按钮与其他3组合在一起,即使它在自己的组框中?
事实上,单选按钮只有在同一个父级内时才是互斥的。 据说我可以想到两个选择。
- 让它们在同一个父级中,处理父级的
Paint
事件并手动绘制自己,给人的印象是它们是不同的组。 - 你必须手动管理互斥:(
RadioButtons并不神奇,它们只是在幕后将其他无线电的Checked
属性设置为false。
private List radioButtons = new List (); //Populate this with radios interested, then call HookUpEvents and that should work private void HookUpEvents() { foreach(var radio in radioButtons) { radio.CheckedChanged -= PerformMutualExclusion; radio.CheckedChanged += PerformMutualExclusion; } } private void PerformMutualExclusion(object sender, EventArgs e) { Radio senderRadio = (RadioButton)sender; if(!senderRadio.Checked) { return; } foreach(var radio in radioButtons) { if(radio == sender || !radio.Checked) { continue; } radio.Checked = false; } }
它们在不同的容器中,所以你无法做到。 我认为这是这个问题的一个骗局: Radiobuttons作为一组在不同的面板
这个问题谈到它:
跨越不同面板的VB.NET组电台按钮
您可以处理单选按钮的CheckedChanged
事件以完成您的需要:
public partial class Form1 : Form { public Form1() { InitializeComponent(); this.radioButton1.CheckedChanged += new System.EventHandler(this.HandleCheckedChanged); this.radioButton2.CheckedChanged += new System.EventHandler(this.HandleCheckedChanged); this.radioButton3.CheckedChanged += new System.EventHandler(this.HandleCheckedChanged); } private bool changing = false; private void HandleCheckedChanged(object sender, EventArgs e) { if (!changing) { changing = true; if (sender == this.radioButton1) { this.radioButton2.Checked = !this.radioButton1.Checked; this.radioButton3.Checked = !this.radioButton1.Checked; } else if (sender == this.radioButton2) { this.radioButton1.Checked = !this.radioButton2.Checked; this.radioButton3.Checked = !this.radioButton2.Checked; } else if (sender == this.radioButton3) { this.radioButton1.Checked = !this.radioButton3.Checked; this.radioButton2.Checked = !this.radioButton3.Checked; } changing = false; } } }