■ DataTemplate 엘리먼트를 사용해 리소스로 데이터 템플리트를 사용하는 방법을 보여준다.
▶ PersonModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
namespace TestProject { /// <summary> /// 사람 모델 /// </summary> public class PersonModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 이름 - Name /// <summary> /// 이름 /// </summary> public string Name { get; set; } #endregion #region 나이 - Age /// <summary> /// 나이 /// </summary> public int Age { get; set; } #endregion #region 위치 - Location /// <summary> /// 위치 /// </summary> public string Location { get; set; } #endregion } } |
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:TestProject"> <ContentPage.Resources> <DataTemplate x:Key="PersonDataTemplateKey"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Label Grid.Column="0" FontAttributes="Bold" Text="{Binding Name}" /> <Label Grid.Column="1" Text="{Binding Age}" /> <Label Grid.Column="2" HorizontalTextAlignment="End" Text="{Binding Location}" /> </Grid> </DataTemplate> </ContentPage.Resources> <CollectionView ItemTemplate="{StaticResource PersonDataTemplateKey}" HorizontalOptions="Center" VerticalOptions="Center" Margin="10"> <CollectionView.ItemsSource> <x:Array Type="{x:Type local:PersonModel}"> <local:PersonModel Name="Steve" Age="21" Location="USA" /> <local:PersonModel Name="John" Age="37" Location="USA" /> <local:PersonModel Name="Tom" Age="42" Location="UK" /> <local:PersonModel Name="Lucas" Age="29" Location="Germany" /> <local:PersonModel Name="Tariq" Age="39" Location="UK" /> <local:PersonModel Name="Jane" Age="30" Location="USA" /> </x:Array> </CollectionView.ItemsSource> </CollectionView> </ContentPage> |