『WPF』DataGrid的使用

几点说明


  • 这里主要是参考了MSDN中关于DataGrid的说明
  • 这里只会简单说明在WPF中,DataGird最简单的使用方法
  • 对于MSDN中的翻译不会很详细,也不会每一句都翻译。

 

来自MSDN的内容


TypeNameDescription
ConstructorsDataGridInitializes a new instance of the System.Windows.Controls.DataGrid class.
PropertyItemsSourceGets or sets a collection that is used to generate the content of the control.
 AutoGenerateColumns Gets or sets a value that indicates whether columns are created automatically when the ItemsSource property is set.

 

The DataGrid control provides a flexible way to display a collection of data in rows and columns. The built-in column types include a text box column, a check box column, and a template column for hosting custom content. The built-in row type includes a drop-down details section that you can use to display additional content below the cell values.

内建的列类型包括:

  1. 文本框
  2. 复选框
  3. 模板列

内建的行类型包括:

  • 下拉列表

image

Binding to Data

To bind the DataGrid to data, set the ItemsSource property to an IEnumerable implementation. Each row in the data grid is bound to an object in the data source, and each column in the data grid is bound to a property of the data object. In order for the DataGrid user interface to update automatically when items are added to or removed from the source data, the DataGrid must be bound to a collection that implements INotifyCollectionChanged, such as an ObservableCollection(Of T). In order to automatically reflect property changes, the objects in the source collection must implement the INotifyPropertyChanged interface.

绑定数据

  1. 设置ItemsSource属性为一个IEnumerable接口的实现(作为数据源)
  2. DataGird中的每一行都绑定到在数据源中的一个对象,每一列都绑定到数据对象中的一个属性
  3. 为了使用户接口能够在items增加或减少时能够从数据源自动更新,DataGrid必须绑定到一个INotifyCollectionChanged接口的实现集上,就像ObservableCollection(Of T)
  4. 为了自动反应属性的变化,在数据源中的对象集必须实现INotifyPropertyChanged接口。
绑定数据using System.Windows;
using System.Collections.ObjectModel;

namespace csdemo.wpf.controls.DataGrid
{
    /// <summary>
    /// DataGridWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DataGridWindow : Window
    {
        public DataGridWindow()
        {
            InitializeComponent();
            dtgrdDisplay.DataContext = gridList;
        }
        ObservableCollection<GirdDataItem> gridList = new ObservableCollection<GirdDataItem>();
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            GirdDataItem item = new GirdDataItem();
            item.id = gridList.Count + 1;
            item.item = tbItem.Text.Trim();

            gridList.Add(item);
        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            gridList.Clear();
            dtgrdDisplay.ItemsSource = null;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }

    public class GirdDataItem
    {
        private int _id;

        public int id
        {
            get { return _id; }
            set { _id = value; }
        }
        private string _item;

        public string item
        {
            get { return _item; }
            set { _item = value; }
        }
    }
}



 

Columns

By default, the DataGrid control generates columns automatically when you set the ItemsSource property. The generated columns are of type DataGridCheckBoxColumn for bound Boolean (and nullable Boolean) properties, and of type DataGridTextColumn for all other properties. If a property does not have a String or numeric value type, the generated text box columns are read-only and display the data object's ToString value.

You can prevent automatic column generation by setting the AutoGenerateColumns property to false. This is useful if you want to create and configure all columns explicitly. Alternatively, you can let the data grid generate columns, but handle the AutoGeneratingColumn event to customize columns after creation. To rearrange the display order of the columns, you can set the DisplayIndex property for individual columns. For more information, see How to: Customize Auto-Generated Columns in the DataGrid Control.

Generated columns recognize the DisplayAttribute if it is present on the source object. The DisplayAttribute.ShortName property is used to specify column header text. The DisplayAttribute.Order property is used to specify the order in which columns appear. The DisplayAttribute.AutoGenerateField property is used to specify whether the field has a column generated for it. For more information, see Using Data Annotations to Customize Data Classes.

Regardless of whether you generate columns, you can use the DataGrid.Columns collection to programmatically add, insert, remove, and change any columns in the control at run time. Alternatively, you can specify columns in XAML, in which case you should set AutoGenerateColumns to false. Creating your own columns enables you to use additional column types, such as the DataGridTemplateColumn type or custom column types. The DataGridTemplateColumn type provides an easy way to create a simple custom column. The CellTemplate and CellEditingTemplate properties enable you to specify content templates for both display and editing modes.

  1. 默认的,当你设置ItemsSource属性时,DataGird控件自动生成列。生成的列中,DataGirdCheckBoxColumn对应绑定Boolean类型的属性,DataGridTextColumn对应所有的其他类型属性。如果一个属性没有一个字符或数值型的值字段,生成的文本框是只读的,并且显示以ToString形式的数据对象。
  2. 你可以通过设置AutoGenerateColumns属性为false来阻止自动生成列。
  3. 你可以通过设置数据源对象的DisplayAttribute属性来控制生成对象的显示方式。 (这个没弄明白怎么搞……)
  4. 关于如何使用Annotation,我另写了一个文章,也是大体上是Copy的「MSDN」,并将其中我认为比较关键的地方做了粗糙翻译。「文章链接」「2012年2月20日改」
  5. 无论你是否使用自动生成列,你都可以通过使用DataGrid.Columns在运行时控制列的添加、插入、移除等。
  6. 你也可以在XAML中指定列。同时,AutoGenerateColumns属性也是在XAML中设置的。

 

Grouping, Sorting, and Filtering

To group, sort, and filter data in the DataGrid, you bind the DataGrid to an ICollectionView implementation that supports these operations. You then perform the operations on the collection view. When data is grouped in the DataGrid, you can customize the appearance of the row group headers with the RowGroupHeaderStyles property. Groups can be expanded and collapsed manually, or programmatically with the ExpandRowGroup and CollapseRowGroup methods. For more information, see How to: Group, Sort, and Filter Data in the DataGrid Control.

分组,排序,过滤

  1. 你可以绑定DataGird到一个ICollectionView的实现,以便在DataGrid中进行分组、排序、过滤

 

Editing

By default, you can edit items directly in the DataGrid. To guarantee that edits can be committed and canceled correctly, the objects in the DataGrid must implement the IEditableObject interface. Alternatively, you can set the IsReadOnly property to true to disable editing in the DataGrid.

A cell level edit is committed when you move to another cell in the same row. All edits in a row are committed when you press ENTER or move to another row. You cancel a cell edit by pressing ESC one time, and cancel all edits in a row by pressing ESC two times. For more information about programmatically committing and canceling edits, see the CommitEdit and CancelEdit methods. For more information about edit related events, see BeginningEdit, PreparingCellForEdit, CellEditEnding, CellEditEnded, RowEditEnding, and RowEditEnded.

编辑

  1. 默认情况下,可以直接在DataGrid中编辑对象。
  2. 为了保证编辑后的对象能够被正确提交,在DataGrid中的对象必须实现IEditableObject接口。你也可以指定IsReadOnly属性为true,以便关闭在DataGrid中的编辑功能。
  3. 单元格级别的编辑,在你转到同行的另一个单元格的时候,被提交。当你按下Enter键的时候,整行都被提交。你可以使用按ESC键两次来取消编辑。

Validation

The DataGrid supports cell-level property validation and row-level object validation. If a validation exception is encountered in the property setter, the cell editing control displays its error state. The DataGridCell.IsValid, DataGridRow.IsValid, and DataGrid.IsValid properties are all set to false. The DataGrid will not exit cell editing mode until the validation error is resolved.

When the row edit is committed, each cell is validated again. In addition, if the object that the row is bound to has a ValidationAttribute, validation is performed on the object. If object validation errors are found, the DataGridRow.IsValid, and DataGrid.IsValid properties are set to false The DataGrid has a built-in ValidationSummary where row-level errors are displayed. The DataGrid will not exit row editing mode until the validation errors are resolved. In order for validation to work correctly, each DataGridBoundColumn.Binding must have its ValidatesOnExceptions and NotifyOnValidationError properties set to true, and its UpdateSourceTrigger set to Explicit.

验证

  1. DataGrid支持单元格级别的属性验证和行级别的对象验证。
  2. 如果 DataGridCell.IsValid DataGridRow.IsValid DataGrid.IsValid 属性全被设置为false。
  3. 在验证出的错误没有被解决,那么就不会离开单元格的编辑状态。
  4. 如果行的编辑被提交了,每一个单元格都会被重新验证。

Paging

To page data in the DataGrid, you bind the DataGrid to an IPagedCollectionView implementation that supports paging operations. You can use a DataGrid with a DataPager control and a data source wrapped in the PagedCollectionView class to easily add paging to your DataGrid.

分页

  1. 在DataGrid上分页显示数据,你绑定DataGird到一个IPagedCollectionView接口实现来支持分页操作。
  2. 你可以配合DataGrid与DataPager控件和一个数据源覆盖到PagedColletionView类来添加分页到你的DataGrid.

 

Customizing the DataGrid Control

The DataGrid control supports common table formatting options, such as alternating row backgrounds and the ability to show or hide headers, grid lines, and scroll bars. Additionally, the control provides several style and template properties that you can use to completely change the appearance of the control and its rows, columns, headers, and cells.

To customize DataGrid behavior, you can handle events for selection change, cell editing, and column re-ordering. The DataGrid also exposes several events for row recycling that you can handle to further customize rows. For more information, see Walkthrough: Customizing the DataGrid Control Using Properties.

To apply the same property settings to multiple DataGrid controls, use the Style property. To change the visual structure and visual behavior of a DataGrid, copy and modify its default style and template. For more information, see Control Customization.

Dependency properties for this control might be set by the default style of the control. If a dependency property for a DataGrid is set by its default style, the property might change from its default value when the DataGrid appears in the application. For more information, see Dependency Property Value Precedence. You can get the default style and template for DataGrid from DataGrid Styles and Templates.

定制DataGrid控件

  1. http://msdn.microsoft.com/en-us/library/cc903951(v=vs.95).aspx

 

XAML<!-- NOTE: 
  By convention, the sdk prefix indicates a URI-based XAML namespace declaration 
  for Silverlight SDK client libraries. This namespace declaration is valid for 
  Silverlight 4 only. In Silverlight 3, you must use individual XAML namespace 
  declarations for each CLR assembly and namespace combination outside the scope 
  of the default Silverlight XAML namespace. For more information, see the help 
  topic "Prefixes and Mappings for Silverlight Libraries". 
-->
<UserControl x:Class="DataGridSnippets.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <ScrollViewer VerticalScrollBarVisibility="Auto" BorderThickness="0" Padding="0">
    <StackPanel Margin="10,10,10,10">

        <TextBlock Text="DataGrid with autogenerated columns:"/>
        <sdk:DataGrid x:Name="dataGrid1" 
            Height="140" Margin="0,5,0,10"
            AutoGenerateColumns="True" />            

        <TextBlock Text="DataGrid with row details sections:"/>
        <sdk:DataGrid x:Name="dataGrid3" 
            Height="140" Margin="0,5,0,10"
            RowDetailsVisibilityMode="VisibleWhenSelected" >            
            <sdk:DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock FontSize="12" Text="Address: " />
                        <TextBlock FontSize="12" Text="{Binding Address}"/>
                    </StackPanel>
                </DataTemplate>
            </sdk:DataGrid.RowDetailsTemplate>                
        </sdk:DataGrid>

        <TextBlock Text="DataGrid with configured columns:"/>
        <sdk:DataGrid x:Name="dataGrid4" 
            Height="160" Margin="0,5,0,10" 
            RowHeight="40" AutoGenerateColumns="False" >    
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn 
                    Header="First Name" 
                    Width="SizeToHeader"
                    Binding="{Binding FirstName}" 
                    FontSize="20" />
                <sdk:DataGridTextColumn 
                    Header="Last Name" 
                    Width="SizeToCells"
                    Binding="{Binding LastName}" 
                    FontSize="20" />
                <sdk:DataGridTextColumn 
                    Header="Address"
                    Width="150"
                    Binding="{Binding Address}" >
                    <sdk:DataGridTextColumn.ElementStyle>
                        <Style TargetType="TextBlock">
                            <Setter Property="TextWrapping" Value="Wrap"/>
                        </Style>
                    </sdk:DataGridTextColumn.ElementStyle>
                    <sdk:DataGridTextColumn.EditingElementStyle>
                        <Style TargetType="TextBox">
                            <Setter Property="Foreground" Value="Blue"/>
                        </Style>
                    </sdk:DataGridTextColumn.EditingElementStyle>
                </sdk:DataGridTextColumn>
                <sdk:DataGridCheckBoxColumn 
                    Header="New?" 
                    Width="40"
                    Binding="{Binding IsNew}" />
                <sdk:DataGridCheckBoxColumn 
                    Header="Subscribed?" 
                    Width="Auto"
                    Binding="{Binding IsSubscribed}" 
                    IsThreeState="True" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>

        <TextBlock Text="DataGrid with template column and custom alternating row backgrounds:"/>
        <sdk:DataGrid x:Name="dataGrid5" 
            Height="125" Margin="0,5,0,10"
            AutoGenerateColumns="False"
            RowBackground="Azure"
            AlternatingRowBackground="LightSteelBlue">
            <sdk:DataGrid.Columns>
                <!-- Name Column -->
                <sdk:DataGridTemplateColumn Header="Name">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                                <TextBlock Padding="5,0,5,0"
                                    Text="{Binding FirstName}"/>
                                <TextBlock Text="{Binding LastName}"/>
                            </StackPanel>
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate> 
                    <sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBox Text="{Binding FirstName}" BorderThickness="0"/>
                                <TextBox Text="{Binding LastName}" BorderThickness="0"/>
                            </StackPanel>
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellEditingTemplate> 
                </sdk:DataGridTemplateColumn>              
                <!-- Address Column -->
                <sdk:DataGridTextColumn
                    Header="Address" Width="300"
                    Binding="{Binding Address}" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
    </StackPanel>
    </ScrollViewer>
</UserControl>

C#using System;
using System.Collections.Generic;
using System.Windows.Controls;

namespace DataGridSnippets
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            // Set the ItemsSource to autogenerate the columns.
            dataGrid1.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid3.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid4.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid5.ItemsSource = Customer.GetSampleCustomerList();
        }
    }

    public class Customer
    {
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Address { get; set; }
        public Boolean IsNew { get; set; }

        // A null value for IsSubscribed can indicate 
        // "no preference" or "no response".
        public Boolean? IsSubscribed { get; set; }

        public Customer(String firstName, String lastName, 
            String address, Boolean isNew, Boolean? isSubscribed)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Address = address;
            this.IsNew = isNew; 
            this.IsSubscribed = isSubscribed;
        }

        public static List<Customer> GetSampleCustomerList()
        {
            return new List<Customer>(new Customer[4] {
                new Customer("A.", "Zero", 
                    "12 North Third Street, Apartment 45", 
                    false, true), 
                new Customer("B.", "One", 
                    "34 West Fifth Street, Apartment 67", 
                    false, false),
                new Customer("C.", "Two", 
                    "56 East Seventh Street, Apartment 89", 
                    true, null),
                new Customer("D.", "Three", 
                    "78 South Ninth Street, Apartment 10", 
                    true, true)
            });
        }
    }
}

转载于:https://www.cnblogs.com/sitemanager/archive/2012/02/18/2357565.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
完整版:https://download.csdn.net/download/qq_27595745/89522468 【课程大纲】 1-1 什么是java 1-2 认识java语言 1-3 java平台的体系结构 1-4 java SE环境安装和配置 2-1 java程序简介 2-2 计算机中的程序 2-3 java程序 2-4 java类库组织结构和文档 2-5 java虚拟机简介 2-6 java的垃圾回收器 2-7 java上机练习 3-1 java语言基础入门 3-2 数据的分类 3-3 标识符、关键字和常量 3-4 运算符 3-5 表达式 3-6 顺序结构和选择结构 3-7 循环语句 3-8 跳转语句 3-9 MyEclipse工具介绍 3-10 java基础知识章节练习 4-1 一维数组 4-2 数组应用 4-3 多维数组 4-4 排序算法 4-5 增强for循环 4-6 数组和排序算法章节练习 5-0 抽象和封装 5-1 面向过程的设计思想 5-2 面向对象的设计思想 5-3 抽象 5-4 封装 5-5 属性 5-6 方法的定义 5-7 this关键字 5-8 javaBean 5-9 包 package 5-10 抽象和封装章节练习 6-0 继承和多态 6-1 继承 6-2 object类 6-3 多态 6-4 访问修饰符 6-5 static修饰符 6-6 final修饰符 6-7 abstract修饰符 6-8 接口 6-9 继承和多态 章节练习 7-1 面向对象的分析与设计简介 7-2 对象模型建立 7-3 类之间的关系 7-4 软件的可维护与复用设计原则 7-5 面向对象的设计与分析 章节练习 8-1 内部类与包装器 8-2 对象包装器 8-3 装箱和拆箱 8-4 练习题 9-1 常用类介绍 9-2 StringBuffer和String Builder类 9-3 Rintime类的使用 9-4 日期类简介 9-5 java程序国际化的实现 9-6 Random类和Math类 9-7 枚举 9-8 练习题 10-1 java异常处理 10-2 认识异常 10-3 使用try和catch捕获异常 10-4 使用throw和throws引发异常 10-5 finally关键字 10-6 getMessage和printStackTrace方法 10-7 异常分类 10-8 自定义异常类 10-9 练习题 11-1 Java集合框架和泛型机制 11-2 Collection接口 11-3 Set接口实现类 11-4 List接口实现类 11-5 Map接口 11-6 Collections类 11-7 泛型概述 11-8 练习题 12-1 多线程 12-2 线程的生命周期 12-3 线程的调度和优先级 12-4 线程的同步 12-5 集合类的同步问题 12-6 用Timer类调度任务 12-7 练习题 13-1 Java IO 13-2 Java IO原理 13-3 流类的结构 13-4 文件流 13-5 缓冲流 13-6 转换流 13-7 数据流 13-8 打印流 13-9 对象流 13-10 随机存取文件流 13-11 zip文件流 13-12 练习题 14-1 图形用户界面设计 14-2 事件处理机制 14-3 AWT常用组件 14-4 swing简介 14-5 可视化开发swing组件 14-6 声音的播放和处理 14-7 2D图形的绘制 14-8 练习题 15-1 反射 15-2 使用Java反射机制 15-3 反射与动态代理 15-4 练习题 16-1 Java标注 16-2 JDK内置的基本标注类型 16-3 自定义标注类型 16-4 对标注进行标注 16-5 利用反射获取标注信息 16-6 练习题 17-1 顶目实战1-单机版五子棋游戏 17-2 总体设计 17-3 代码实现 17-4 程序的运行与发布 17-5 手动生成可执行JAR文件 17-6 练习题 18-1 Java数据库编程 18-2 JDBC类和接口 18-3 JDBC操作SQL 18-4 JDBC基本示例 18-5 JDBC应用示例 18-6 练习题 19-1 。。。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值