【发布时间】:2020-02-11 18:56:11
【问题描述】:
Xamarin 新手。从另一个表/模型/对象显示我需要的数据的最佳方式是什么?还是根本没有?
我想尝试 System.Linq 的 Enumerable.Join 但这不会破坏可观察集合的目的吗?我想更改内容并插入记录。我一直在尝试使用其他模型将信息组合在一起,但没有成功。
尝试使用轮播视图,其中包含围绕信息的另一个组模型。问题来自工作 API。谢谢大家。
问题
- q问题
- 姓名
回答
- 答案
- f问题
- 价值
- 评论
视图模型
IEnumerable<QuestionModel> questions = await DataSource.GetQuestionsAsync(true);
QuestionList.Clear();
int k = 0;
foreach (var i in q)
{
// questions for template
QuestionList.Add(i);
var c = k++;
string s = (c + 1).ToString();
var a = new AnswerModel
{
pAnswer = s,
Posted = DateTime.Now,
fQuestion = i.pQuestion,
Value = i.Standard,
Comments = "Commnt here"
};
// template of answers for each question
AnswerCollection.Add(a);
}
// templates
foreach (var i in AnswerCollection)
{
var n = new GroupList<QuestionModel>
{
pGroup = i.pQuestion.ToString(),
Name = i.Name
};
n.Add(i);
GroupedAnswerCollection.Add(n);
}
//var g = AnswerCollection.Join(
// QuestionList,
// foreign => foreign.fQuestion,
// primary => primary.pQuestion,
// (primary, foreign) => new
// {
// Test = primary.pAnswer,
// Test2 = foreign.Name,
// }).ToList();
Xaml
<CarouselView ItemsSource="{Binding GroupedCollection}"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame BorderColor="DarkGray"
Margin="20"
WidthRequest="200"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand">
<StackLayout>
<StackLayout>
<Label Text="{Binding pGroup}"></Label>
<Label Text="{Binding Name}"></Label>
<Label Text="{Binding Other}"></Label>
</StackLayout>
<StackLayout>
<Label Text="{Binding pAnswer}"></Label>
<Label Text="{Binding fQuestion}" ></Label>
<Label Text="{Binding Value}" ></Label>
<Label Text="{Binding Comments}" ></Label>
</StackLayout>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
【问题讨论】:
-
你在哪里设置
GroupedCollection?DataTemplate中的绑定将具有构成GroupedCollection的模型的绑定上下文。看起来您正在尝试绑定到答案中的属性,但也在问题中。那是行不通的。有没有您没有在示例中添加的组合模型? -
我在循环中创建了组列表。这就是我所得到的。我在构造函数上也有一个新的 ObservableCollection。你是这个意思吗?此外,如果它不起作用。我应该怎么做?我正在学习,我还需要学习正确的方法。
-
很难从这个问题中看出你到底想要达到什么。但简而言之。 ViewModel 的目的是处理和格式化数据,以便通过简单的属性绑定从 View 轻松使用数据。
-
明白了。好的,所以我的问题是视图模型是否与数据只有一对一的关系?还是可以一对多?我正在寻找在同一个视图中显示每个问题(问题模型)和一个答案(答案模型),所以如果它是 sql 中的一个 select 语句,它将是 pQuestion、Name、pAnswer、Value、来自 Answer Inner 的评论的结果在 Answer.fQuestion 上加入问题 = Question.pQuestion
-
viewmodel 与数据有一对多的关系。它可以来自任意数量的来源。视图与视图模型(其绑定上下文)具有一对一的关系,但默认情况下 DataTemplates 具有不同的绑定上下文。
标签: templates xamarin mvvm carousel observablecollection