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; }
}
}

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

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

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

小结

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



标签:WPF

相关阅读 >>

WPF教程之 treeview简介

WPF教程之 为贪吃蛇添加食物

WPF教程之 播放视频

WPF中自定义gridlengthanimation的实例教程

WPF教程之 触发器动画

WPF教程之 richtextbox控件

WPF教程之 image控件

WPF教程之 border控件

WPF教程之 grid控件

WPF教程之 window

更多相关阅读请进入《WPF》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...