0

I have an observable collection which gives values to radio buttons. As the user moves from one item to another, I would like the corresponding group radio button to be automatically selected if the user previously selected it.

To summarize it's a multiple question type exam and i want to keep the radio button selected as the user navigates from one question to another.

Here's the view:

<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>

The observable collection:

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

    }

The Model:

public List<string> Choices
    {
        get 
        {
            if (_choices == null)
                _choices = new List<string>();

            return _choices; 
        }
        set
        {
            if (_choices != value)
            {
                _choices = value;
                OnPropertyChanged("Choices");
            }
        }
    }
Mike
  • 37
  • 14

2 Answers2

0

I solved this by using this approach MVVM: Binding radio buttons to a view model? and binding the SelectedItem property with the value of the selected radio button.

The selected radio button is kept track on one of the fields of my observable collection CurrentQuestion.StudentAnswer.

Community
  • 1
  • 1
Mike
  • 37
  • 14
0

There is interesting article how to deal with RadioButton binding in many ways.

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

myś
  • 94
  • 1
  • 5