[英]How do I use a radiobutton's function (one button click, the others clear automatically) to other controls
First, I apologize for my insufficient English-skill. 首先,我对我的英语水平不足表示歉意。
I'm creating my own image button, and I want to make my control interact with each other like a radiobutton controls. 我正在创建自己的图像按钮,并且希望使控件彼此之间像单选按钮控件一样进行交互。
When the user selects one option button (also known as a radio button) within a group, the others should be cleared automatically. 当用户在组中选择一个选项按钮(也称为单选按钮)时,其他选项按钮应自动清除。
In this situation, here are two images ( 1m.png
, 2m.png
). 在这种情况下,这是两个图像(
1m.png
, 2m.png
)。 If I click one image button, image changes to 1m.png
, while the others automatically change their image to 2m.png
. 如果单击一个图像按钮,图像将更改为
1m.png
,而其他图像会自动将其图像更改为2m.png
。
Thank you for reading and please help! 感谢您的阅读,请提供帮助!
You can achieve it by overriding OnClick event. 您可以通过覆盖OnClick事件来实现。 I've just written this code and it works smoothly.
我刚刚编写了这段代码,它运行顺利。 I did tested by changing the BackColor of the control.
我通过更改控件的BackColor进行了测试。 Based on your needs, you can change the Image, the BackgroundImage or any other property.
根据您的需要,您可以更改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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.