简体   繁体   English

每个RadioButton触发事件

[英]firing Event for every RadioButton

I'm creating a radio button in C# code for a WinRT application. 我正在使用WinRT应用程序的C#代码创建一个单选按钮。

My code: 我的代码:

for(var l = 0; l < 4; l++) {
    RadioButton radio = new RadioButton();
    radio.Checked += (sender,arg)=>{ //sender };
    stackpanel.children.add(radio);
}

Now I add those radio buttons in page and I need to know which radio button is checked but when event fires it's sent to me only the last button. 现在,我在页面中添加了这些单选按钮,我需要知道选中了哪个单选按钮,但是当event触发时,仅将最后一个按钮发送给我。 How do I make an event for every button so that when someone checks Button 1 I can send a message box: "you checked button 1"? 如何使一个事件的每个按钮,这样,当有人检查Button 1 ,我可以发送一个消息框:“你检查按钮1”?

Use the CheckChangedEvent. 使用CheckChangedEvent。 Try to use this in your for-loop: 尝试在您的for循环中使用它:

     RadioButton radio = new RadioButton();
                 radio.Name = "Button" + l;
                 radio.CheckedChanged += Radio_CheckedChanged; 

And then when the event is triggered do the following: 然后在触发事件时执行以下操作:

    /// <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"); 
        }
    }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM