问题描述
我是 Avalonia 的新手,我需要为我的一个项目生成问题和答案列表。到目前为止,我已经根据需要生成了问题和答案。 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>
我现在想要的是根据我从 AnswerType
列表中获得的 Questions
值创建不同类型的回答选项(单选按钮或复选框)。这是我的问题模型
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; }
}
样本数据
{
"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"
}
解决方法
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,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>