Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple RadioButton groups in ItemsControl

I'm working on a small project that displays answers for a survey. I'm having an issue displaying answers for options questions.

As you can see in the xaml extract below, I'm trying to group radio button by the answer id so only one option is selected per answer object.

However, the code below treats all of radio button in the whole survey as part of one big radiobutton group and only allows the selection of one option for all questions.

Let's say, i have 2 answers to display (- = not selected, + = selected):

I expect something like this:

Answer1:

-Option1 - Option2 + Option3

Answer2:

-Option1 + Option2 - Option3

But the xaml code below only allowing me to have one selected value from both questions instead of forcing mutual exclusivity per question.

<ItemsControl ItemsSource="{Binding Options}">
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <RadioButton GroupName="{Binding AnswerId}" Content="{Binding Option}" IsChecked="{Binding IsSelected, Mode=OneWay}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
like image 602
aamran Avatar asked Nov 13 '22 20:11

aamran


1 Answers

I created a test using your Xaml and the following code and it works fine (allows one selection from each group of 3 answers):

enter image description here

Are you creating all the answer options before binding? It looks like GroupName is not a dependency property.

using System.Collections.Generic;
namespace PersonTests
{
    public class QuestionTestViewModel
    {
        public IEnumerable<AnswerOption> Options { get; set; }

        public QuestionTestViewModel()
        {
            this.Options = new List<AnswerOption>()
                            {
                                new AnswerOption(){AnswerId = 1, Option = "One A", IsSelected = false},
                                new AnswerOption(){AnswerId = 1, Option = "One B", IsSelected = false},
                                new AnswerOption(){AnswerId = 1, Option = "One C", IsSelected = false},
                                new AnswerOption(){AnswerId = 2, Option = "Two A", IsSelected = false},
                                new AnswerOption(){AnswerId = 2, Option = "Two B", IsSelected = false},
                                new AnswerOption(){AnswerId = 2, Option = "Two C", IsSelected = false}
                            };
        }
    }

    public class AnswerOption
    {
        public int AnswerId { get; set; }
        public string Option { get; set; }
        public bool IsSelected { get; set; }
    }
}
like image 95
Gone Coding Avatar answered Dec 28 '22 23:12

Gone Coding