WPF教程之 DataGrid 控件

DataGrid 控件:

DataGrid 控件

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

DataGrid控件非常常见的使用场景是能够显示每行的详细信息,通常位于本行的正下方。 WPF的DataGrid控件对这一点支持得非常好,幸运的是它也非常易于使用。 我们先从一个例子开始,然后讨论它是如何工作的,最后讨论他提供的选项。

一个简单的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; }
}
}


WPF教程之 DataGrid 控件

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

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

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

小结

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

作者:terry,如若转载,请注明出处:https://www.web176.com/wpf/15967.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年4月19日
下一篇 2023年4月19日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注