在DataGrid的开发设计中,我们经常要对DataGrid中的数据进行统计,而统计的结果往往放置在DataGrid的底部,这就需要使用脚模板来对其进行处理。可是问题在于Silverlight并未提供现成的脚模板。于是,本文将为大家介绍如何为DataGrid添加设置脚模板。
需要了解的知识
我们知道DataGrid有一个十分重要的属性ItemsSource,它的作用是获取或设置被用于生成该控件内容的集合(Collection)。这也就是说,它代表了DataGrid中所有数据项的集合。
通过对其进行操作,我们便能够容易地得到统计数据。
具体步骤
1)确定要进行统计的数据列
2)运用StackPanel或Grid结合进行脚模板的构造
3)遍历DataGrid的ItemsSource的所有需要统计的数据列,进行数据汇总
4)将结果传递至脚模板显示
实例
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;
int total = 0;
foreach (object o in dgEmployee.ItemsSource)
{
Products item = o as Products;
total += item.Total;
}
dataTotal.Text = "总计:" + total.ToString();
}
}
}
最终效果图
