簡體   English   中英

如何知道所選單選按鈕的索引

[英]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 而是使用匿名方法實際收到的內容 ,即oSender

為單選按鈕組上的索引更改創建事件。 之后,創建一個單獨的函數來反序列化您的XML文件。 將從XML文件獲得的給定整數傳遞給索引更改事件,然后相應地顯示UI元素。 確保比較單選按鈕的.selectedIndex屬性上的整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM