Datagrid 是做企业应用必不可少的利器。在这里说一句题外话,有人说做了几年都是数据库增删改查,从事的工作毫无新意。我只能说,你看问题的方式还停留在 数据 方面,以 数据 为中心向 领域模型 为中心转换是开发人员思考问题的进步。数据库只是持久化的工具而已啦,当然你从事的项目一直复杂度不高,业务比较简单的话,可能也会有这样的感觉。ERP 、 CRM 那个不是增删改查,这些大公司不也是封装了产品在卖吗?学习的好还能评MVP呢。 好了,废话结束,让我们来开始 DataGrid !
1,DataGrid 的数据源
通过 ItemsSource 属性来指定,必须为实现了 IEnumerable 接口的集合类。
托拽一个DataGird 到 MainPage.xaml
在Code behind 我们添加
public MainPage()
{
InitializeComponent();
this.dataGrid1.ItemsSource = "H el l o w o r l d !".Split();
}
F5 ,屏幕显示如下,当然别忘了把 AutoGenerateColumns 设为 True
或者 this.dataGrid1.ItemsSource = new int[] { 1, 2, 3, 4, 5 }; 也可以看一下结果.
下面我们来实践一下使用 List 存放具体业务数据的例子:
我们给Silverlight 所在项目(不是 web application)添加一个 Customer Class
public class Customer
{public string FirstName { get; set; }public string LastName { get; set; }public int Age { get; set; }public bool Available { get; set; }}在Code behind 我们添加
public MainPage(){InitializeComponent();List<Customer> source = new List<Data>();F5 :
int itemsCount = 100;
for (int i = 0; i < itemsCount; i++)
{
source.Add(new Customer()
{
FirstName = "First",
LastName = "Last",
Age = i,
Available = (i % 2 == 0)
});
}
dataGrid1.ItemsSource = source;
}
我们并没有自己设计任何Column,都是Datagrid根据数据类型自己生成的,下一篇我们会详细介绍如何定制Column
关于数据源注意,dataGrid in Silverlight 并不支持 Datatable 作为数据源。有些开发者可能觉得这样不是很方便,关于如何支持 Datatable 有其他的很多文章又阐述,需要的话自己可以搜索一下。
但是我觉得不用 Datatable 未必是一件坏事,这样的我们的程序可以更加 OO,当然代价也是有的,就是封装对象时可能增加我们的工作量。
还有相对于ASP 的 datagirdview , Datagrid in silverlight 的优势应该在用户体验上,这方面我也会继续研究,做出更绚的效果。