我在WinRT应用程序的C#代码中创建一个单选按钮。
我的代码:
for(var l = 0; l < 4; l++) {
RadioButton radio = new RadioButton();
radio.Checked += (sender,arg)=>{ //sender };
stackpanel.children.add(radio);
}
现在我在页面中添加了这些单选按钮,我需要知道选中了哪个单选按钮,但是当event
触发它时,它只发送给我最后一个按钮。如何为每个按钮创建一个事件,以便当有人检查Button 1
时我可以发送一个消息框:&#34;您选中了按钮1&#34;?
答案 0 :(得分:0)
使用CheckChangedEvent。尝试在你的for循环中使用它:
RadioButton radio = new RadioButton();
radio.Name = "Button" + l;
radio.CheckedChanged += Radio_CheckedChanged;
然后在触发事件时执行以下操作:
/// <summary>
/// This will trigger all changes to the CheckedState - even unchecking
/// </summary>
private void Radio_CheckedChanged(object sender, EventArgs e)
{
RadioButton checkedRadioButton = (RadioButton) sender;//Cast the sender of the event back to RadioButton
if (checkedRadioButton.Checked)//Only do this when checking - not on unchecking
{
MessageBox.Show($"You checked {checkedRadioButton.Name}", "Pressed");
}
}