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; }
}
}