最簡單示範
在頁面中定義 ListView
<ListView x:Name="MyListView"
Width="350"
Height="400" />
在 C# 中建立清單,並放入資料:
List<string> users = new List<string>();
users.Add("小明");
users.Add("阿花");
users.Add("老王");
users.Add("小李");
users.Add("阿張");
users.Add("小林");
MyListView.ItemsSource = users;
自訂顯示內容格式
並不是所有清單都是單純的字串,很常會遇到是物件的情況,也可能有多個內容要顯示,這時候就可以使用 DataTemplate 來自訂資料的顯示方式:自訂類別:
public class UserDto
{
public int Id { get; set; }
public string Name { get; set; }
}
自訂資料清單:
List<UserDto> users = new List<UserDto>();
users.Add(new UserDto { Id = 1, Name = "小明" });
users.Add(new UserDto { Id = 2, Name = "阿花" });
users.Add(new UserDto { Id = 3, Name = "老王" });
users.Add(new UserDto { Id = 4, Name = "小李" });
users.Add(new UserDto { Id = 5, Name = "阿張" });
users.Add(new UserDto { Id = 6, Name = "小林" });
MyListView.ItemsSource = users;
使用 DataTemplate 定義每筆資料的顯示方式,並在 ListView 上使用 ItemTemplate 設定樣式:
<Page
x:Class="WinUi3ListViewTest.Views.Page3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:winUi3ListViewTest="using:WinUi3ListViewTest"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<DataTemplate x:Key="ListViewItemTemplate" x:DataType="winUi3ListViewTest:UserDto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Ellipse x:Name="Ellipse"
Grid.RowSpan="2"
Width="32"
Height="32"
Margin="6"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Fill="{ThemeResource SystemControlBackgroundBaseMediumBrush}" />
<TextBlock Grid.Row="0" Grid.Column="1"
Text="{x:Bind Id}"
x:Phase="1"
Style="{ThemeResource BaseTextBlockStyle}"
Margin="12,6,0,0" />
<TextBlock Grid.Column="1" Grid.Row="1"
Text="{x:Bind Name}"
x:Phase="2"
Style="{ThemeResource BodyTextBlockStyle}"
Margin="12,0,0,6" />
</Grid>
</DataTemplate>
</Page.Resources>
<ListView x:Name="MyListView"
ItemTemplate="{StaticResource ListViewItemTemplate}"
Width="350"
Height="400" />
</Page>
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com