65.9K
CodeProject 正在变化。 阅读更多。
Home

WPF DataGrid 入门

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.68/5 (45投票s)

2008年8月12日

CPOL

2分钟阅读

viewsIcon

352204

downloadIcon

4310

介绍如何在 WPF 中使用新的 DataGrid 的文章

引言

WPF 发布之初没有 DataGrid,微软因此受到了很多批评!他们终于发布了备受期待的 DataGrid (CTP)! 以下是关于如何使用 DataGrid 的简短介绍

必需

这里 下载 WPFToolkit

要运行我的示例应用程序,还需要安装 Northwind 数据库

入门

创建一个空白的 WPF 应用程序,并添加一个新的项目 (LINQ-to-SQL 类)。将 Northwind 数据库中所需的表拖放到设计界面上

LINQ2SQL.jpg

现在我们有了可以使用的简单数据库,让我们将 DataGrid 添加到我们的项目中。添加对 WPFToolkit.dll 的引用,并将命名空间添加到主窗口的 XAML 中

xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit"

我们可以创建的最简单的 DataGrid 就是在窗口中添加 DataGrid 并将 AutoGenerateColumns 设置为 True!这将为表中的每个字段自动生成一列。我还给 DataGrid 起了一个名字,以便可以在代码中访问它

<dg:DataGrid 
    x:Name="NorthwindDataGrid"
    AutoGenerateColumns="True" />

现在剩下的就是从数据库中获取表 (使用我创建的 LINQ-to-SQL 类),并将 DataGrid 的 ItemSource 设置为该表 (DataGrid 继承自 ItemsControl)

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    using (NorthwindDataContext dc = new NorthwindDataContext())
    {
        NorthwindDataGrid.ItemsSource = dc.Customers.ToList();
    }
}

DataGrid 在其鼎盛时期是这样的…

DataGrid.jpg

这很简单,这个宝贝还能做什么?

默认情况下,DataGrid 支持调整大小、重新排序、排序、添加和删除。可以使用以下属性控制此行为

  • CanUserAddRows
  • CanUserDeleteRows
  • CanUserResizeColumns
  • CanUserReorderColumns
  • CanUserSortColumns

编辑单元格时,会触发以下事件…

  • PreparingCellForEdit
  • BeginningEdit
  • CommitingEdit
  • CancelingEdit

DataGrid 继承自 MultiSelector,允许真正的多行选择场景。选择模式通过将 SelectionMode 设置为 Single 或 Extended 来控制

SelectionUnit 也可以更改为仅选择单元格 (DataGridSelectionUnit.Cell)、行 (DataGridSelectionUnit.FullRow) 或单元格/行 (DataGridSelectionUnit.CellOrRowHeader)

DataGrid 完全支持剪贴板复制/粘贴

更多资源

  • 阅读有关 DataGrid 的完整功能列表的更多信息 这里
  • Vincent Sibal 在他的博客上也有一些关于该主题的优秀内容

和往常一样,请为这篇文章投票 (如果您觉得它很糟糕,请留下评论告诉我如何改进它)

Rudi Grobler

http://dotnet.org.za/rudi

历史

2008-08-12 - 发布初始版本

© . All rights reserved.