■ ListBox 엘리먼트의 ItemTemplate 속성을 사용하는 방법을 보여준다.
▶ 예제 코드 (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 |
<Grid x:Name="grid" xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" Background="White"> <Grid.Resources> <DataTemplate x:Key="DataTemplateKey"> <StackPanel Margin="5" Orientation="Horizontal"> <Ellipse Width="10" Height="10" VerticalAlignment="Center"> <Ellipse.Fill> <SolidColorBrush Color="{Binding GroupColor}" /> </Ellipse.Fill> </Ellipse> <TextBlock Margin="5 0 0 0" Text="{Binding Name}" /> <TextBlock Text="(" /> <TextBlock Text="{Binding ID}" /> <TextBlock Text=")" /> </StackPanel> </DataTemplate> </Grid.Resources> <ListBox x:Name="listBox" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="200" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemTemplate="{StaticResource DataTemplateKey}"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <controls:WrapPanel /> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> </Grid> |
▶ Student.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 39 |
using System.Windows.Media; /// <summary> /// 학생 /// </summary> public class Student { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> public string Name { get; set; } #endregion #region 클래스 색상 - ClassColor /// <summary> /// 클래스 색상 /// </summary> public Color ClassColor { get; set; } #endregion } |
▶ MainPage.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System.Collections.Generic; using System.Windows.Media; ... List<Student> list = new List<Student>(); list.Add(new Student() { ID = 1, Name = "가", ClassColor = Colors.Red }); list.Add(new Student() { ID = 2, Name = "나", ClassColor = Colors.Blue }); list.Add(new Student() { ID = 3, Name = "다", ClassColor = Colors.Red }); list.Add(new Student() { ID = 4, Name = "라", ClassColor = Colors.Green }); ... this.listBox.ItemsSource = list; |