首页 > 解决方案 > 获取.net中选中的单选按钮列表

问题描述

TLDR;寻找一种通过类似这样的方式检索所有单选按钮的方法......(psudo)

    List<RadioButton> btn = new List<RadioButton>;
    btn = stackPanel.getAllRadioButtons()

我目前正在用 C# 构建一个小测验应用程序。我有将所需的 GUI 元素添加到组框的功能。我想知道是否有任何方法可以遍历创建的元素(例如单选按钮)以查看哪些被选中。

这是其中一项功能以及如何将它们添加到窗口中。

    private void tfQ(string questionBody)
    {
        StackPanel questionPanel = new StackPanel{Orientation = Orientation.Vertical};
        questionPanel.Children.Add(new Label { Content = questionBody });
        GroupBox group = new GroupBox();
        RadioButton trueRadio = new RadioButton();
        trueRadio.Content = "True";
        RadioButton falseRadio = new RadioButton();
        falseRadio.Content = "False";
        questionPanel.Children.Add(trueRadio);
        questionPanel.Children.Add(falseRadio);
        group.Content = questionPanel;
        mainStack.Children.Add(group);


    }

构造函数:

    public quiz()
    {
        tfQ("This is a true/false question");
        Window w = new Window();
        w.Content = mainStack;
        w.Show();
    }

我发现了很多方法可以用 C# 脚本格式来实现

(使用控制功能...)

     var checkedButton = container.Controls.OfType<RadioButton>()
                                  .FirstOrDefault(r => r.Checked);

但我还没有找到一种“程序化”的方式来做到这一点。我考虑过将 void tfQ 的类型更改为 StackPanel,但这只会帮助我更轻松地遍历堆栈面板,尽管这只能部分解决我的问题 - 让我更容易地遍历 StackPanel,但我仍然不知道如何获取面板上的 RadioButtons。

PS 我对 C# 很陌生 - 有 Java/C/C++/Python 方面的经验

标签: c#.net

解决方案


我使用以下代码将内容分别转换为新的 groupbox 和 stackpanel。

    if (child is GroupBox)
    {
       if ((child as GroupBox).Content is StackPanel)
       {
           StackPanel d = (StackPanel)((GroupBox)child).Content; 
       }

     }

这使我可以将内容转换为控件的本地副本。这可能不是最好的方法——老实说,我敢肯定这是非常低效的。解决了这个问题。


推荐阅读