TOC

This article has been localized into Chinese by the community.

DataGrid 控件:

DataGrid 控件

在使用GridView时,DataGrid控件看起来很像ListView,但是它提供了许多附加的功能。 例如,DataGrid可以自动生成列,具体取决于您提供的数据。 DataGrid默认也是可编辑的,它允许最终用户更改底层数据源的值。

DataGrid最常见的使用场景是与数据库结合,不过就像大多数WPF控件一样,DataGrid也能与驻留于内存中的数据源(例如一个object类型的List)良好的结合。为了让演示更简易,我们将在本教程中使用内存中的数据源,不涉及数据库。

一个简单的DataGrid

您可以在不设置任何属性的情况下开始使用DataGrid,因为它支持非常多的开箱即可用功能。 在第一个例子中,我们将会这样做,然后把我们自己的User(用户)对象的列表设为项目源(ItemsSource):

<Window x:Class="WpfTutorialSamples.DataGrid_control.SimpleDataGridSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SimpleDataGridSample" Height="180" Width="300">
    <Grid Margin="10">
<DataGrid Name="dgSimple"></DataGrid>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Windows;

namespace WpfTutorialSamples.DataGrid_control
{
public partial class SimpleDataGridSample : Window
{
public SimpleDataGridSample()
{
InitializeComponent();

List<User> users = new List<User>();
users.Add(new User() { Id = 1, Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new User() { Id = 2, Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new User() { Id = 3, Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });

dgSimple.ItemsSource = users;
}
}

public class User
{
public int Id { get; set; }

public string Name { get; set; }

public DateTime Birthday { get; set; }
}
}

这就是您开始使用DataGrid所需做的。数据源可以仅仅是一个数据库表/视图,甚至是一个XML文件 - DataGrid对于从何处获取数据并不挑剔。

如果您单击其中一个单元格,则可以看到默认情况下,它允许您编辑每个属性。 作为一个不错的小红利,您可以尝试单击一个列标题 - 您将看到DataGrid支持立即排序!

最后一行空行将允许您添加一行到数据源,只需填写单元格即可。

小结

如您所见,开始使用DataGrid非常地容易,但它也是一个高度可定制的控件。 在接下来的章节中,我们将研究所有您可以使用DataGrid完成的所有很酷的事情,请继续阅读。


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!