【问题标题】:MVVM Keeping track of selected Radio ButtonMVVM 跟踪选定的单选按钮
【发布时间】:2015-01-11 21:04:07
【问题描述】:

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

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

这是视图:

<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");
            }
        }
    }

【问题讨论】:

    标签: c# wpf mvvm data-binding radio-button


    【解决方案1】:

    我通过使用这种方法 MVVM: Binding radio buttons to a view model? 并将 SelectedItem 属性与所选单选按钮的值绑定来解决了这个问题。

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

    【讨论】:

      【解决方案2】:

      有一篇有趣的文章how to deal with RadioButton binding in many ways.

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-27
        • 1970-01-01
        • 2020-09-04
        • 1970-01-01
        • 2011-02-12
        • 2017-11-18
        • 2014-06-19
        • 1970-01-01
        相关资源
        最近更新 更多