Reputation: 173
I'm new to Avalonia and I need to generate a List of Questions and answers for one of my projects. Up to now I have generated the Questions and and Answers as I needed. Code for the XAML
<ItemsControl Items="{Binding Questions}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock
Classes="header"
Text="{Binding QuestionDescription}"
TextWrapping="Wrap" />
<ItemsControl Items="{Binding Answers}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="{Binding AId}" Content="{Binding Answer}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
What I want now is to create different type of answering options (Radiobutton or checkbox) depending on the AnswerType
value that I get from the Questions
List. Here is my Question model
public class Question
{
public string QId { get; set; }
public string QuestionDescription { get; set; }
public List<Answers> Answers { get; set; }
public string AnswerType { get; set; }
}
public class Answers
{
public string AId { get; set; }
public string Answer { get; set; }
}
Sample data
{
"QId": "Q1",
"QuectionDescription": "Quection01",
"Answers": [
{
"AId": "Q1A1",
"Answer": "Yes"
},
{
"AId": "Q1A2",
"Answer": "No"
}
],
"AnswerType": "RadioButton"
},
{
"QId": "Q2",
"QuectionDescription": "Quection02",
"Answers": [
{
"AId": "Q2A1",
"Answer": "Football"
},
{
"AId": "Q2A2",
"Answer": "Baseball"
}
],
"AnswerType": "CheckBox"
}
Upvotes: 3
Views: 3282
Reputation: 3623
public class TemplateDictionaryConverter : Dictionary<string, IDataTemplate>, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string s)
return this[s];
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
<ItemsControl Items="{Binding Answers}">
<ItemsControl.ItemTemplate>
<Binding
Path="AnswerType">
<Binding.Converter>
<example:TemplateDictionaryConverter>
<DataTemplate x:Key="CheckBox">
<CheckBox Content="{Binding Answer}" />
</DataTemplate>
<DataTemplate x:Key="RadioButton">
<RadioButton Content="{Binding Answer}" />
</DataTemplate>
</example:TemplateDictionaryConverter>
</Binding.Converter>
</Binding>
</ItemsControl.ItemTemplate>
</ItemsControl>
Upvotes: 3