MVVM 跟踪选定的单选按钮

本文关键字:单选按钮 跟踪 MVVM | 更新日期: 2023-09-27 18:37:01

我有一个可观察的集合,它为单选按钮提供值。当用户从一个项目移动到另一个项目时,如果用户之前选择了相应的组单选按钮,我希望自动选择它。

总而言之,这是一个多问题类型的考试,我想在用户从一个问题导航到另一个问题时保持单选按钮处于选中状态。

这是视图:

<ItemsControl ItemsSource="{Binding CurrentQuestion.Choices}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <RadioButton Content="{Binding .}" 
                                 Command="{Binding DataContext.SaveAnswerCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
                                 CommandParameter="{Binding}"
                                 GroupName="choices"
                                 />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

可观察集合:

public static ObservableCollection<ExamModel> Questions
    {
        get
        {
            return _questions;
        }
        set
        {
            _questions = value;
        }
    }
//this is how i keep track of which item is currently active
public ExamModel CurrentQuestion
    {
        get { return _currentQuestion; }
        set
        {
            if (_currentQuestion != value)
            {
                _currentQuestion = value;
                OnPropertyChanged("CurrentQuestion");
            }
        }
    }

模型:

public List<string> Choices
    {
        get 
        {
            if (_choices == null)
                _choices = new List<string>();
            return _choices; 
        }
        set
        {
            if (_choices != value)
            {
                _choices = value;
                OnPropertyChanged("Choices");
            }
        }
    }

MVVM 跟踪选定的单选按钮

我通过使用此方法解决了这个问题 MVVM:将单选按钮绑定到视图模型?,并将 SelectedItem 属性与所选单选按钮的值绑定。

所选单选按钮在我的可观察集合 CurrentQuestion.StudentAnswer 的一个字段中保持跟踪。

有一篇有趣的文章如何以多种方式处理RadioButton绑定。

在Windows上看Jerry Nixon:让我们编码吧!数据绑定到 XAML 中的单选按钮