[英]How to know the index of radiobutton selected
如何知道单选按钮的选择索引,以了解用户选择了哪个索引选项。
目前,我的代码显示已读取的项目。 但是,当我选择出现的项目时,它会在文本块中显示单选按钮的所选项目(给定3个选项,因为我的单选按钮当前有3个项目)。
我的尝试是:
foreach (String item in param.Parameter[lop].Component.Attributes.Items)
{
RadioButton radio = new RadioButton()
{
Content = item,
GroupName = "MyRadioButtonGroup"
};
radio.Checked += (o, e) =>
{
txtblkShowStatus.Text = item;
};
data= param.Parameter[lop].Label;
sp.Children.Add(radio);
}
现在我想要类似“基于项目”的选择,现在我想要基于索引的渗透。 我想要类似的东西。 如果用户选择第二个按钮(单选按钮),那么我将显示一些UI元素。 这些项目是在反序列化xml时获得的。 仅处理单选按钮的索引。 所以我想要类似if(selectedIndexofRadioButton ==IndexObtainedFromXmlInIntegr){do something}
有可能吗? 如果是,那我应该如何更改我的代码来实现呢? 编辑:DonBoitnott的答案编辑后,我的代码更改为:
foreach (String item in param.Parameter[lop].Component.Attributes.Items)
{
RadioButton radio = new RadioButton()
{
Content = item,
GroupName = "MyRadioButtonGroup",
Tag=tg
};
radio.Checked += (o, e) =>
{
txtblkShowStatus.Text = item;
if (((Int32)((RadioButton)o).Tag).Equals(2))
{
MessageBox.Show("hurrey");
}
};
radio.Tag=1;
data= param.Parameter[lop].Label;
sp.Children.Add(radio);
index++; tg++;
}
您应该利用RadioButton
控件对象的Tag
属性:
foreach (String item in param.Parameter[lop].Component.Attributes.Items)
{
RadioButton radio = new RadioButton()
{
Content = item,
GroupName = "MyRadioButtonGroup",
Tag = //integer value from XML
};
radio.Checked += (o, e) =>
{
txtblkShowStatus.Text = item;
};
data = param.Parameter[lop].Label;
sp.Children.Add(radio);
}
Tag
属性是一个Object
,因此您可以为其分配任何内容。 您只需要在使用它时将其抛弃即可:
if (((Int32)radioButton.Tag).Equals(IndexObtainedFromXmlInInteger)
{
//do something
}
针对您的评论,OP:
radio.Checked += (o, e) =>
{
txtblkShowStatus.Text = item;
if (((Int32)((RadioButton)o).Tag).Equals(2))
{
MessageBox.Show("hurrey");
}
};
您错误地尝试使用上面声明的radio
。 而是使用匿名方法实际收到的内容 ,即o
或Sender
。
为单选按钮组上的索引更改创建事件。 之后,创建一个单独的函数来反序列化您的XML文件。 将从XML文件获得的给定整数传递给索引更改事件,然后相应地显示UI元素。 确保比较单选按钮的.selectedIndex属性上的整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.