ListView 是一个控件,允许您动态显示项目列表,以便用户可以滚动该项目列表以查看它们并找到他们可能需要的任何内容。在 XAML 中定义它真的很简单:
<ListView x:Name="StudentsList" />
现在,假设您有一份大学生名单。每个学生都有一个简单的学生类。
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
可能有数十、数百或数千名学生,因此您无法静态定义 UI。您通常将这些学生保留在代码隐藏中的某种列表/集合中。您可以从各种来源获取它们——数据库、Web 服务或硬编码,就像我现在出于演示目的所做的那样:
private List<Student> listOfStudents = new List<Student>();
public MainPage()
{
this.InitializeComponent();
listOfStudents.Add(new Student { Name = "John", Age = 20 });
listOfStudents.Add(new Student { Name = "Bob", Age = 21 });
listOfStudents.Add(new Student { Name = "Steve", Age = 19 });
listOfStudents.Add(new Student { Name = "Marko", Age = 18 });
listOfStudents.Add(new Student { Name = "Igor", Age = 20 });
listOfStudents.Add(new Student { Name = "Ivan", Age = 20 });
listOfStudents.Add(new Student { Name = "Nina", Age = 21 });
listOfStudents.Add(new Student { Name = "Paul", Age = 20 });
listOfStudents.Add(new Student { Name = "Ana", Age = 23 });
listOfStudents.Add(new Student { Name = "Ivana", Age = 20 });
StudentsList.ItemsSource = listOfStudents;
}
该列表/集合用作 ListView 的项目源,因此您设置 ListView 的 ItemsSource 属性以连接两者并在 UI 中显示列表。使用 ListView 动态呈现所有项目,而不管项目的数量。
如果我们现在运行这个应用程序,它会很丑:
你需要定义一个DataTemplate 让它更漂亮。由于每个学生都有姓名和年龄,因此您将希望使用这些属性使其看起来更漂亮。这个DataTemplate 被分配给ListView.ItemTemplate 属性,ListView 将为列表中的每个项目使用它。
<ListView x:Name="StudentsList">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"
Margin="20,0,20,8"
FontSize="24"
FontStyle="Italic"
FontWeight="SemiBold"
Foreground="DarkBlue" />
<TextBlock Text="{Binding Age}"
Margin="20,0,20,8"
FontSize="16"
Foreground="DarkGray"
Opacity="0.8" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
看,我使用 DataTemplate 来定义要显示的属性以及如何呈现它们 - 我使用了字体大小、字体颜色、边距等。我承认这并不是那么漂亮,但我相信你会明白的:
您会注意到的另一件事是我使用了这样的绑定结构:
<TextBlock Text="{Binding Name}" ... />
这基本上意味着:检查对象是否具有属性Name,如果有,则将其呈现为TextBlock.Text。
请注意,事情可能会变得更加复杂,因此您可以为一个列表中的不同项目使用不同的模板等。但这不在我认为的问题范围内。
TLDR:ListView 动态呈现项目列表。 ItemsSource 定义了 ListView 的项目来源。 DataTemplate 定义了一个用于渲染某些东西的模板。这个DataTemplate 被分配给ListView 的ItemTemplate 属性,以便ListView 知道它应该使用该模板来呈现其项目。