c# - 获取.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 方面的经验
解决方案
我使用以下代码将内容分别转换为新的 groupbox 和 stackpanel。
if (child is GroupBox)
{
if ((child as GroupBox).Content is StackPanel)
{
StackPanel d = (StackPanel)((GroupBox)child).Content;
}
}
这使我可以将内容转换为控件的本地副本。这可能不是最好的方法——老实说,我敢肯定这是非常低效的。解决了这个问题。
推荐阅读
- reactjs - 任何人都可以解释如何使用 react 和 axios 添加新配方?
- kubernetes - kubernets pod 在挂载之前使用 configmap
- xamarin.android - 我想用事件制作滑块来捕获 Xamarin.Android 中的值
- sql - 过程问题 SQL Server 出现错误
- android - 创建的工具栏无法在 Android 设备上正确显示
- css - 打字稿的 CSS 界面
- android - 如果在 CoordinatorLayout 中设置了anchorView,则浮动操作按钮不与 Snackbar 一起浮动
- java - 我无法在我的 android 模拟器中接收 Firebase Cloud Messaging FCM
- macos - 如何在 Mac 上安装 Tesseract 5.0.0 alpha?
- c++ - 如何从启动时最大化cpp程序中的窗口?