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