WPF 模板主要分為兩大類:
1.ControlTemplate: 控件的外觀,也就是控件是什么樣子。
2.DataTemplate: 是數據內容的表現,一條數據顯示成什么樣子。
(1)DataTemlate數據模板常用的地方有以下幾處:
1.ContentControl的ContentTemplate屬性
2.ItemsControl的ItemTemplate屬性。
3.GridViewColumn的CellTemplate屬性。
2. 實例代碼
<Window x:Class="WpfApplication18.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel x:Name="stackPanel">
<ListBox Margin="10" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" Margin="10"></TextBlock>
<TextBlock Text="{Binding Path=Score}" Margin="10"></TextBlock>
<CheckBox IsChecked="{Binding Path=Gender}" Margin="10"></CheckBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication18
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var students = new List<Student>
{
new Student{Name="Jack",Score=80,Gender=true},
new Student{Name="Tom",Score=60,Gender=false},
new Student{Name="David",Score=80,Gender=true},
};
this.stackPanel.DataContext = students;
}
}
public class Student
{
public string Name { get; set; }
public int Score { get; set; }
public bool Gender { get; set; }
}
}
