[英]How to get behavior like a radio button group so only one item can be selected
I made a user control and placed it in a panel. 我做了一个用户控件,并将其放在面板中。 The user control has its own mouse click event that changes color.
用户控件具有其自己的更改颜色的鼠标单击事件。 If I click on a control on the panel, I want the other controls to be deselected.
如果单击面板上的控件,则希望取消选择其他控件。 Like radio buttons.
像单选按钮一样。 How can I do that?
我怎样才能做到这一点?
Here is a picture of my panel. 这是我的面板的图片。 There is both of two user controls is selected.
选择了两个用户控件。
public partial class list : UserControl
{
void chgtxt(Label lbl, string s)
{
lbl.Text = s;
}
public list()
{
InitializeComponent();
}
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
panel1.BackColor = Color.Yellow;
chgtxt(label1, "Changed");
}
}
You can enumerate the panel's children and deselect the ones that aren't the current control: 您可以枚举面板的子级,然后取消选择不是当前控件的子级:
foreach (list listControl in Parent.Controls.Cast<Control>().OfType<list>())
{
if (list != this)
{
list.Deselect();
}
}
Then you just have to create a Deselect()
method on your control: 然后,您只需要在控件上创建
Deselect()
方法:
public void Deselect()
{
// Do whatever to show this control as deselected.
}
To expand on itsme86's answer , you need to look at the parent control your control is part of and deselect the other items in the list. 要扩展itsme86的答案 ,您需要查看控件所属的父控件,然后取消选择列表中的其他项。
public partial class list : UserControl
{
void chgtxt(Label lbl, string s)
{
lbl.Text = s;
}
public list()
{
InitializeComponent();
}
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
panel1.BackColor = Color.Yellow;
chgtxt(label1, "Changed");
if(this.Parent != null)
{
foreach (list listControl in this.Parent.Controls.Cast<Control>().OfType<list>())
{
if (listControl != this)
{
listControl.Deselect();
}
}
}
}
private void Deselect()
{
// Do whatever to show this control as deselected.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.