在我的 QuestionsPage
中,我在另一个 ListView (QuestionsListView
) 内有一个 ListView
(AnswersListView
)。
如何在 AnswersListView
的 ItemsSource
中引用问题的索引(位于 QuestionsListView 中)?
为了让它更清楚,这是一个简化的代码...我想用问题的索引替换 ???
。
希望大家能够理解。
在我的 XAML 中:
<ListView x:Name="QuestionsListView"
ItemsSource="{Binding Challenge.questions}"
<ListView.ItemTemplate>
<DataTemplate>
<ListView x:Name="AnswersListView"
ItemsSource="{Binding Challenge.questions[???].answers, Source={x:Reference QuestionsPage}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<local:AnswerButton Text="{Binding isCorrect}" Command="{Binding BindingContext.CheckAnswerCommand, Source={x:Reference QuestionsPage}" CommandParameter="{Binding isCorrect}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
还有我的模型(了解一个模型与另一个模型之间的关系):
public class ChallengeModel {
public int challengeId { get; set; }
public string challengeName { get; set; }
public ObservableCollection<Question> questions { get; set; }
public ChallengeModel() { }
}
public class Question {
public string questionText { get; set; }
public ObservableCollection<Answer> answers { get; set; }
public Question() { }
}
public class Answer {
public bool isCorrect { get; set; }
public string answerText { get; set; }
public Answer() { }
}
最佳答案
您不必从原始 DataContext
引用它。使用 ItemsSource
实质上是将 Challenge.question
属性设置为列表的数据源。现在,当您定义 ListView.ItemTemplate
时,您实际上处于列表中的一个问题的上下文中。因此,DataTemplate
中的每个 {Binding}
都与问题本身相关(除非您另外指定)。
这意味着,您只需使用{Bindinganswers}
将内部列表绑定(bind)到可用答案列表:
<ListView x:Name="QuestionsListView"
ItemsSource="{Binding Challenge.questions}"
<ListView.ItemTemplate>
<DataTemplate>
<ListView x:Name="AnswersListView"
ItemsSource="{Binding answers}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<local:AnswerButton Text="{Binding isCorrect}" Command="{Binding BindingContext.CheckAnswerCommand, Source={x:Reference QuestionsPage}" CommandParameter="{Binding isCorrect}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
关于listview - 如何将 ListView 中元素的索引绑定(bind)到第一个 ListView 内第二个 ListView 的 ItemsSource 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48451840/