C# 在Xamarin.Forms中,以纯文本形式显示viewmodel列表的最简单方式是什么?
在Xamarin.Forms应用程序中。我想让视图以纯文本形式显示ViewModel中的对象列表。我看到过这样使用列表视图的示例C# 在Xamarin.Forms中,以纯文本形式显示viewmodel列表的最简单方式是什么?,c#,xamarin.forms,mvvm,C#,Xamarin.forms,Mvvm,在Xamarin.Forms应用程序中。我想让视图以纯文本形式显示ViewModel中的对象列表。我看到过这样使用列表视图的示例 <ListView x:Name="ItemView" ItemsSource="{Binding Items}"> <ListView.ItemTemplate> <DataTemplate> <TextCell Te
<ListView x:Name="ItemView"
ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Text}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
StudentDetailViewModel.cs
public class Student
{
public string Id { get; set; }
public string Name { get; set; }
public ICollection<Course> Courses{ get; set; }
}
public class Course
{
public string Id { get; set; }
public string Name { get; set; }
public string CourseNumber { get; set; }
}
[QueryProperty(nameof(StudentId), nameof(StudentId))]
public class StudentDetailViewModel : BaseViewModel
{
private string studentId;
private string name;
private ICollection<Courses> courses;
public string Id { get; set; }
public string Name
{
get => name;
set => SetProperty(ref name, value);
}
public ICollection<Course> Courses
{
get => Courses;
set => SetProperty(ref courses, value);
}
public string StudentId
{
get
{
return studentId;
}
set
{
studentId = value;
LoadStudentId(value);
}
}
public async void LoadStudentId(string sId)
{
try
{
var student = await DataStore.GetItemAsync(sId);
Id = student.Id;
Name = student.Name;
Courses = student.Courses;
}
catch (Exception)
{
Debug.WriteLine("Failed to Load Item");
}
}
}
但是,当我尝试使用ListView方法时,我不知道如何设置TextCell的
Text=“{Binding PropName}”
属性的格式,以便在这个“{Prop1}-{Prop2}”格式中使用两个属性。使用CollectionView,我根本不知道如何正确绑定数据以显示它。显示这样的内容最简单的方法是什么?设置我的ViewModel来实现这一点的最佳实践是什么?有很多方法可以实现这一点。最简单的方法可能是使用ViewCell
来包含带有span
的标签,而不是TextCell
。您还可以使用集合视图
执行类似操作,该视图不需要使用单元格
<ListView ItemsSource="{Binding Courses}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding Name}" />
<Span Text=" - " />
<Span Text="{Binding CourseNumber}" />
</FormattedString>
<Label.FormattedText>
</Label>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
学生信息可以放在课程前的单独版面中,也可以添加到课程中。您是要显示一个学生及其课程,还是要显示多个学生及其每个学生的课程列表?@Jason在这种情况下,我试图列出一个学生及其课程列表。谢谢!这对我来说非常合适。我想我只需要更加熟悉XAML中可用的单元格和视图的类型。不过,你没有给它贴上结束标签。您可能需要更新您的响应以确保准确性。
Student Name
Courses:
* CourseNumber - CourseName
* CourseNumber - CourseName
* CourseNumber - CourseName
<ListView ItemsSource="{Binding Courses}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding Name}" />
<Span Text=" - " />
<Span Text="{Binding CourseNumber}" />
</FormattedString>
<Label.FormattedText>
</Label>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>