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&g开发者_Go百科t;
I created a test using your Xaml and the following code and it works fine (allows one selection from each group of 3 answers):
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; }
}
}
Could you maybe post the object/class definition that you are binding to, it's a bit unclear as to how your data structure is working. I've built a questionnaire is Silverlight, had a similar challenge...
精彩评论