首先在xaml中建立集合是一個不可取的方法。學習
本方法僅做爲xaml的學習。spa
本文略微無聊,主要是編寫的東西都是老玩意。code
首先是定義一個類,做爲你要加載集合的模型。blog
結構以下get
internal class Student { public string Name { get; set; } public int Age { get; set; } } internal class StudentList:List<Student> { } class StringCollect { public StudentList Students { get; set; } }
XAML中string
<Window.DataContext> <local:StringCollect x:Name="c2" > <local:StringCollect.Students> <local:StudentList> <local:Student Age="18" Name="A1"/> <local:Student Age="18" Name="A2"/> <local:Student Age="18" Name="A3"/> </local:StudentList> </local:StringCollect.Students> </local:StringCollect> </Window.DataContext> <Grid> <ListBox ItemsSource="{Binding ElementName=c2,Path=Students}"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <TextBlock> <Run Text="Name:"/> <Run Text="{Binding Name}"/> </TextBlock> <TextBlock Grid.Column="1"> <Run Text="Age:"/> <Run Text="{Binding Age}"/> </TextBlock> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>
截圖以下it
那麼還有別的方法嗎?io
固然了,好比XAML中的X:Array關鍵字class
好比List
<ListBox > <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <TextBlock> <Run Text="Name:"/> <Run Text="{Binding Name}"/> </TextBlock> <TextBlock Grid.Column="1"> <Run Text="Age:"/> <Run Text="{Binding Age}"/> </TextBlock> </Grid> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemsSource> <x:Array Type="{x:Type local:Student}"> <local:Student Age="18" Name="b1"/> <local:Student Age="18" Name="b2"/> <local:Student Age="18" Name="b3"/> </x:Array> </ListBox.ItemsSource> </ListBox>
我以爲在xaml建立集合是一個比較無聊的事情。