WPF模版主要分为俩大类:
ControlTemplate: 控件的外观,也就是控件是什么样子
DataTemplate: 是数据内容的表现,一条数据显示成什么样子
1. 数据模版常用的地方有以下几处:
- ContentControl的ContentTemplate属性。
- ItemsControl的ItemTemplate属性。
- GridViewColumn的CellTemplate属性。
2. 示例
ItemsControl
ContentControl
3. DataTemplate除了可以作用在控件上,也可以作用再数据类型上
<Window x:Class="DeepXAML.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DeepXAML" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:cl="clr-namespace:System.Collections;assembly=mscorlib" Title="MainWindow" Height="250" Width="450"> <Window.Resources> <DataTemplate DataType="{x:Type local:Student}"> <StackPanel Orientation="Horizontal" > <Grid Margin="5"> <Rectangle Fill="YellowGreen" Width="{Binding Path=Score}"/> <TextBlock Text="{Binding Path=Name}"></TextBlock> </Grid> <TextBlock Text="{Binding Path=Score}" Margin="5"></TextBlock> </StackPanel> </DataTemplate> <cl:ArrayList x:Key="allStudentsList"> <local:Student Name="Jack" Gender="True" Score="80"></local:Student> <local:Student Name="Tom" Gender="False" Score="40"></local:Student> <local:Student Name="Jack" Gender="True" Score="75"></local:Student> </cl:ArrayList> </Window.Resources> <StackPanel x:Name="stackPanel"> <ListBox ItemsSource="{StaticResource ResourceKey=allStudentsList}" FontSize="15"></ListBox> <TextBlock Margin="10">Below is combox</TextBlock> <ComboBox ItemsSource="{StaticResource ResourceKey=allStudentsList}" FontSize="15"></ComboBox> </StackPanel> </Window>
4. DataTemplate作用在XML元素上
<Window x:Class="DeepXAML.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DeepXAML" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:cl="clr-namespace:System.Collections;assembly=mscorlib" Title="MainWindow" Height="250" Width="450"> <Window.Resources> <DataTemplate DataType="Student"> <StackPanel Orientation="Horizontal" > <Grid Margin="5"> <Rectangle Fill="YellowGreen" Width="{Binding XPath=@Score}"/> <TextBlock Text="{Binding XPath=@Name}"></TextBlock> </Grid> <TextBlock Text="{Binding XPath=@Score}" Margin="5"></TextBlock> </StackPanel> </DataTemplate> <XmlDataProvider x:Key="xmlDp" XPath="Students/Student"> <x:XData> <Students xmlns=""> <Student Name="Jack" Score="80"></Student> <Student Name="Tom" Score="40"></Student> <Student Name="David" Score="75"></Student> </Students> </x:XData> </XmlDataProvider> </Window.Resources> <StackPanel x:Name="stackPanel"> <ListBox ItemsSource="{Binding Source={StaticResource xmlDp}}" FontSize="15"></ListBox> <TextBlock Margin="10">Below is combox</TextBlock> <ComboBox ItemsSource="{Binding Source={StaticResource xmlDp}}" FontSize="15"></ComboBox> </StackPanel> </Window>