如何通过c#在组中获得选中的单选按钮

本文关键字:单选按钮 何通过 | 更新日期: 2023-09-27 18:09:46

如何通过c#获得位于stackpanel(父容器)内的选定单选按钮控件的索引而不是边框?

这是我搜索和尝试后得到的

 for (int i = 0; i < this.selective.Children.Count; i++)
            {
                if (this.selective.Children[i].GetType().Name == "RadioButton")
                {
                    RadioButton radio = (RadioButton)this.selective.Children[i];
                    if ((bool)radio.IsChecked)
                    {
                        //get checked indes name
                   }
               }
          }

但是这里我有一个单选按钮在边界内那么如何实现相同的

这里是xaml

  <StackPanel Visibility="Collapsed" x:Name="selective" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="462"   >
                    <Border  Margin="20,0,20,0" Grid.Row="2" BorderThickness="2" BorderBrush="Black" >
                        <RadioButton GroupName="main1" x:Name="radio1"   Foreground="#FF030303"   Background="#FF0075A9" />
                    </Border>
                    <Border Margin="20,0,20,0" Grid.Row="2" BorderThickness="2" BorderBrush="Black" >
                        <RadioButton GroupName="main1" x:Name="radio2"   Foreground="#FF030303"   Background="#FF0075A9"  />
                    </Border>
    ....

那么如何知道哪个是选中的呢?

如何通过c#在组中获得选中的单选按钮

我想你可以试试这样做:

foreach (var radioButton in selective.Children.OfType<Border>().Select(b => b.Child).OfType<RadioButton>())
{
    if (((RadioButton)radioButton).IsChecked ?? false)
    {
        //Do stuff
    }
}
<标题>更新答案

下面是获取RadioButton的索引和名称的方法:

var radioButtons = selective.Children.OfType<Border>().Select(b => b.Child).OfType<RadioButton>();
foreach (var radioButton in radioButtons)
{
    if (radioButton.IsChecked ?? false)
    {
        var name = radioButton.Name;
        var index = radioButtons.ToList().IndexOf(radioButton);
    }
}

main1代替this

for (int i = 0; i < main1.selective.Children.Count; i++)
            {
                if (main1.selective.Children[i].GetType().Name == "RadioButton")
                {
                    RadioButton radio = (RadioButton)main1.selective.Children[i];
                    if ((bool)radio.IsChecked)
                    {
                        //get checked indes name
                   }
               }
          }