【问题标题】:How do I use a radiobutton's function (one button click, the others clear automatically) to other controls如何将单选按钮的功能(单击一个按钮,其他按钮自动清除)用于其他控件
【发布时间】:2018-04-11 00:26:16
【问题描述】:
首先,我很抱歉我的英语水平不够。
我正在创建自己的图像按钮,我想让我的控件像单选按钮控件一样相互交互。
当用户选择组内的一个选项按钮(也称为单选按钮)时,其他选项按钮应自动清除。
在这种情况下,这里有两张图片(1m.png、2m.png)。如果我单击一个图像按钮,图像将更改为1m.png,而其他按钮会自动将其图像更改为2m.png。
感谢您的阅读,请帮助!
【问题讨论】:
-
嗨,欢迎来到堆栈溢出。请参阅How to Ask 链接以获取有关如何提出问题并相应更新您的问题的更多详细信息。
-
-
标签:
c#
winforms
radio-button
controls
【解决方案1】:
您可以通过覆盖 OnClick 事件来实现它。我刚刚编写了这段代码,它运行顺利。我通过更改控件的 BackColor 进行了测试。根据您的需要,您可以更改 Image、BackgroundImage 或任何其他属性。
using System;
using System.Linq;
using System.Windows.Forms;
namespace StackOverflow
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
}
public partial class ImageButton : Button
{
//Override OnClick event.
protected override void OnClick(EventArgs e)
{
/*
"Unselect" every ImageButton that belongs to the
same group as the current ImageButton and
select the current one.
*/
do
{
/*
Change Image of current ImageButton.
I'm changing the BackColor for simplicity. You have to remove this line.
*/
this.BackColor = System.Drawing.Color.Green;
//this.BackgroundImage = 1m.png;
//If ImageButton parent is null, then it doesn't belong in a group.
if (this.Parent == null)
break;
/*
Else loop through all other ImageButtons of the same group and clear them.
Include System.Linq for this part.
*/
foreach (ImageButton button in this.Parent.Controls.OfType<ImageButton>())
{
//If button equals to current ImageButton, continue to the next ImageButton.
if (button == this)
continue;
//Else change the Image.
button.BackColor = System.Drawing.Color.Red;
//this.BackgroundImage = 2m.png;
}
}
while (false);
//Continue with the regular OnClick event.
base.OnClick(e);
}
}
}