在DataGrid的开发设计中,我们经常会碰到设计样式各异的表头以满足各种要求。而头模板的作用是显示DataGrid控件的首行中的文本、图片或是绑定数据的。通过对头模板的设定,可以为我们定制所需样式的DataGrid。本文将为大家介绍如何自定义DataGrid的头模板。
具体步骤:
1)在XAML文件中的UserControl标签中加入如下命名空间:
xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
2)设置呈现头模板的样式HeaderStyle的属性
3)可以利用StackPanel标签组合编排添加在头模板内的组件的位置。
实例:
通过实例来了解头模板制定的基本方法。
先来看看效果:

在代码中会指明操作的关键步骤。
MainPage.xaml文件代码:
MainPage.xaml.cs文件代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightClient
{
public class Products
{
public int Quantity { get; set; }
public int Price { get;set;}
public int Total { get; set; }
}
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
List
em1.Add(new Products() { Quantity = 20, Price = 130, Total = 2600 });
em1.Add(new Products() { Quantity = 5, Price=800, Total = 4000 });
em1.Add(new Products() { Quantity = 10, Price=2000, Total = 20000 });
dgEmployee.ItemsSource = em1;
}
}
}