ListView是一种控件,允许您动态地显示一个项目列表,以便用户可以滚动浏览该列表并查找所需的内容。在XAML中定义它非常简单:
<ListView x:Name="StudentsList" />
现在,假设你有一个大学学生列表。每个学生都由一个简单的Student类表示。
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
可能会有几十个、几百个或上千个学生,因此您无法静态定义用户界面。通常情况下,您会在代码后台将这些学生保存在某种列表/集合中。您可以从各种来源获取它们——数据库、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
。
请注意,事情可能会变得更加复杂,因此您可以在一个列表中为不同的项使用不同的模板等,但我认为这不在问题范围内。
简而言之:
ListView
动态呈现一系列项目。
ItemsSource
定义了该
ListView
的项目来源。
DataTemplate
定义了用于呈现某些内容的模板。将此
DataTemplate
分配给
ListView
的
ItemTemplate
属性,以便
ListView
知道它应该使用完全相同的模板来呈现其项目。