You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF C#考试管理项目单选按钮选中状态保存问题求助

解决WPF考试项目单选按钮状态保存与恢复问题

核心问题是你没给每个题目单独存储选中的答案,单个bool变量没法区分不同题目的状态,直接操作控件的话切换时容易丢失数据。用数据绑定的方式来处理最靠谱,步骤如下:

1. 定义题目数据模型

先写一个类来存每个题目的信息和用户选中的答案,让每个题目都有独立的状态:

public class ExamQuestion
{
    public string QuestionText { get; set; }
    public List<string> Options { get; set; }
    // 用索引存储用户选中的选项,-1代表未作答
    public int SelectedOptionIndex { get; set; } = -1;
}

2. 管理所有题目集合

在窗口类里定义题目集合和当前显示的题目,同时设置数据上下文让XAML能绑定到这些属性:

public ObservableCollection<ExamQuestion> AllQuestions { get; set; }
public ExamQuestion CurrentQuestion { get; set; }

public MainWindow()
{
    InitializeComponent();
    // 初始化示例题目
    AllQuestions = new ObservableCollection<ExamQuestion>
    {
        new ExamQuestion
        {
            QuestionText = "题目1:WPF属于哪种框架?",
            Options = new List<string> { ".NET桌面框架", "前端框架", "后端框架", "移动框架" }
        },
        new ExamQuestion
        {
            QuestionText = "题目2:C#中int类型占多少字节?",
            Options = new List<string> { "2", "4", "8", "16" }
        }
    };
    DataContext = this;
}

3. 修改XAML绑定控件

把原来手动创建的单选按钮改成绑定模式,切换题目时自动同步状态:

<!-- 显示当前题目 -->
<TextBlock Text="{Binding CurrentQuestion.QuestionText}" FontSize="16" Margin="10"/>

<!-- 绑定选项到单选按钮 -->
<ItemsControl ItemsSource="{Binding CurrentQuestion.Options}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <RadioButton Content="{Binding}" 
                         IsChecked="{Binding Path=DataContext.SelectedOptionIndex, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Converter={StaticResource OptionIndexConverter}, ConverterParameter={Binding}}"
                         Margin="5"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

<!-- 题目切换按钮 -->
<StackPanel Orientation="Horizontal" Margin="10">
    <Button Content="题目1" Click="BtnQuestion1_Click"/>
    <Button Content="题目2" Click="BtnQuestion2_Click"/>
</StackPanel>

4. 添加索引转换转换器

因为单选按钮的IsChecked是bool类型,而我们存的是int索引,需要转换器关联两者:

public class OptionIndexConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is int selectedIndex && parameter is string option)
        {
            var question = ((FrameworkElement)parameter).DataContext as ExamQuestion;
            return question?.Options.IndexOf(option) == selectedIndex;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((bool)value && parameter is string option)
        {
            var question = ((FrameworkElement)parameter).DataContext as ExamQuestion;
            return question?.Options.IndexOf(option) ?? -1;
        }
        return -1;
    }
}

记得在XAML资源里声明这个转换器:

<Window.Resources>
    <local:OptionIndexConverter x:Key="OptionIndexConverter"/>
</Window.Resources>

5. 切换题目的按钮逻辑

切换时直接更新CurrentQuestion,绑定会自动处理控件状态,不用手动清空:

private void BtnQuestion1_Click(object sender, RoutedEventArgs e)
{
    CurrentQuestion = AllQuestions[0];
    OnPropertyChanged(nameof(CurrentQuestion));
}

private void BtnQuestion2_Click(object sender, RoutedEventArgs e)
{
    CurrentQuestion = AllQuestions[1];
    OnPropertyChanged(nameof(CurrentQuestion));
}

// 实现属性变更通知,让UI同步更新
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

为什么原来的bool变量没用?

单个bool只能记录“是否点击过题目”,但没法区分是哪个题目、选中了哪个选项。每个题目必须有独立的状态存储,用数据模型绑定后,每个题目的选中状态都存在自身属性里,切换时自然就能恢复。

内容的提问来源于stack exchange,提问作者amjad salih

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:20:27