首先在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建立集合是一个比较无聊的事情。