1. 程式人生 > 其它 >WPF資料模板

WPF資料模板

資料模板

資料模板實質上也是以內容模板為基礎,在資料模板中,是對內容模板重複的顯示,以達到迭代顯示資料的作用,所以在資料模板中,可以新增呈現資料的任意元素。能夠新增資料模板的元素,主要是繼承自ItemsControl類的控制元件,通過控制元件的ItemTemplate屬性來支援,比如我們常用的ListBox和ComboBox控制元件

<ListBox Width="300" Height="300" x:Name="studentList" Canvas.Left="166" Canvas.Top="19" HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Margin="5" BorderThickness="2" BorderBrush="DarkSlateBlue" CornerRadius="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" HorizontalAlignment="Stretch" Text="{Binding Path=Name}"></TextBlock>
<TextBlock Grid.Row="1" HorizontalAlignment="Stretch" Text="{Binding Path=Age}"></TextBlock>
<TextBlock Grid.Row="2" HorizontalAlignment="Stretch" Text="{Binding Path=Grade}"></TextBlock>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

//ItemsPanelTemplate 定義了元素與元素之間的佈局

<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>