MVVM 跟踪选定的单选按钮

MVVM Keeping track of selected Radio Button

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

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

视图如下:

<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: Binding radio buttons to a view model? 并将 SelectedItem 属性 与所选单选按钮的值绑定来解决了这个问题。

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

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

Jerry Nixon on Windows: Let’s code! Data binding to a Radio Button in XAML