Introduction

Since .NET 4.0, Microsoft is shipping a DataGrid control that provides all the basic functionality needed, like:

Basic usage: Auto generate columns

To show a basic data grid , just drop a DataGrid control to your view and bind the ItemsSource to a collection of data objects and you're done. The DataGrid provides a feature called AutoGenerateColumns that automatically generates column according to the public properties of your data objects. It generates the following types of columns:

  • TextBox columns for string values
  • CheckBox columns for boolean values
  • ComboBox columns for enumerable values
  • Hyperlink columns for Uri values

  <DataGrid ItemsSource="{Binding Customers}" />    

Manually define columns

Alternatively you can define your columns manually by setting the AutoGenerateColumns property to False. In this case you have to define the columns in the Columns collection of the data grid. You have the following types of columns available:

  • DataGridCheckBoxColumn for boolean values
  • DataGridComboBoxColumn for enumerable values
  • DataGridHyperlinkColumn for Uri values
  • DataGridTemplateColumn to show any types of data by defining your own cell template
  • DataGridTextColumn to show text values

  <DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Image}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>   

Selection

The data grid includes a variety of selection modes. They are configured by the SelectionMode and SelectionUnit property.

  • The SelectionMode can be set to Single or Extended to define if one or multiple units can be selected simultaneously.
  • The SelectionUnit defines the scope of one selection unit. It can be set to Cell, CellAndRowHeader and FullRow.

  <DataGrid ItemsSource="{Binding Customers}"
SelectionMode="Extended" SelectionUnit="Cell" />   

Column sorting, reordering and resizing

The data grid provides features to sort, reorder and resize columns. They can be enabled or disabled by the following properties:

  • CanUserReorderColumns enables or disables column re-ordering
  • CanUserResizeColumns enables or disables column resizing
  • CanUserResizeRows enables or disables row resizing
  • CanUserSortColumns enables or disables column sorting

  <DataGrid ItemsSource="{Binding Customers}"
CanUserReorderColumns="True" CanUserResizeColumns="True"
CanUserResizeRows="False" CanUserSortColumns="True"/>   

Grouping

The data grid also supports grouping. To enable grouping you have to define a CollectionView that contains to least one GroupDescriptionthat defines the criterias how to group.

  Customers = new ListCollectionView(_customers);
Customers.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));   

Second thing you need to do is defining a template how the groups should look like. You can do this by setting the GroupStyle to something like the following snippet.

  <DataGrid ItemsSource="{Binding GroupedCustomers}">
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander>
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=ItemCount}"/>
<TextBlock Text="Items"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>   

Row Details

The data grid provides a feature that shows a detail panel for a selected row. It can be enabled by setting a DataTemplate to theRowDetailsTemplate property. The data template gets the object that is bound to this row passed by the DataContext and can bind to it.

  <DataGrid ItemsSource="{Binding Customers}">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Image Height="100" Source="{Binding Image}" />
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>   
Row Details depending on the type of data

You can specify a RowDetailsTemplateSelector that selects a data template according to the type or data that this row contains. To do this, create a type that derives from DataTemplateSelector and override the SelectTemplate method. In the items argument you get the data and you can determine which data template to display. Return an instance of that data template as return value.

  public class GenderTemplateSelector : DataTemplateSelector
{
public DataTemplate MaleTemplate { get; set; }
public DataTemplate FemaleTemplate { get; set; }   public override DataTemplate SelectTemplate(object item,
DependencyObject container)
{
var customer = item as Customer;
if (customer == null)
return base.SelectTemplate(item, container);   if( customer.Gender == Gender.Male)
{
return MaleTemplate;
}
return FemaleTemplate;
}
}   
  <l:GenderTemplateSelector x:Key="genderTemplateSelector">
<l:GenderTemplateSelector.MaleTemplate>
<DataTemplate>
<Grid Background="LightBlue">
<Image Source="{Binding Image}" Width="50" />
</Grid>
</DataTemplate>
</l:GenderTemplateSelector.MaleTemplate>
<l:GenderTemplateSelector.FemaleTemplate>
<DataTemplate>
<Grid Background="Salmon">
<Image Source="{Binding Image}" Width="50" />
</Grid>
</DataTemplate>
</l:GenderTemplateSelector.FemaleTemplate>
</l:GenderTemplateSelector>   <DataGrid ItemsSource="{Binding Customers}"
RowDetailsTemplateSelector="{StaticResource genderTemplateSelector}" />   

Alternating BackgroundBrush

You can define a an AlternatingRowBackground that is applied every even row. You can additionally specify an AlternationCount if you only want to ink every every n-th data row.

  <DataGrid ItemsSource="{Binding Customers}"
AlternatingRowBackground="Gainsboro" AlternationCount="2"/>   

Frozen Columns

The data grid also supports the feature to freeze columns. That means they stay visible while you scoll horizontally through all columns. This is a useful feature to keep a referencing column like an ID or a name always visible to keep your orientation while scrolling.

To freeze a numer of columns just set the FrozenColumnCount property to the number of columns you want to freeze.

  <DataGrid ItemsSource="{Binding Customers}" FrozenColumnCount="2"  />    

Headers visbility

You can control the visibility of row and column headers by setting the HeadersVisibility property to either None,Row,Column or All

  <DataGrid ItemsSource="{Binding Customers}" HeadersVisibility="None" />    

How to template autogenerated columns

If you want to autogenerate columns using AutoGenerateColumns="True", you cannot use CellTemplates, because the DataGridautogenerates either a text, combo, hyperlink or checkbox column, but none of these are templateable. A simple workaround is to hook into the autogeneration, cancel it and always create a DataGridTemplateColumn. The following snippet shows the idea (the code is just a draft):

  public class MyDataGrid : DataGrid
{   public DataTemplateSelector CellTemplateSelector
{
get { return (DataTemplateSelector)GetValue(CellTemplateSelectorProperty); }
set { SetValue(CellTemplateSelectorProperty, value); }
}   public static readonly DependencyProperty CellTemplateSelectorProperty =
DependencyProperty.Register("Selector", typeof(DataTemplateSelector), typeof(MyDataGrid),
new FrameworkPropertyMetadata(null));       protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
{
e.Cancel = true;
Columns.Add(new DataGridTemplateColumn
{
Header = e.Column.Header,
CellTemplateSelector = CellTemplateSelector
});
}
}   
  <l:MyDataGrid ItemsSource="{Binding}"
AutoGenerateColumns="True"
CellTemplateSelector="{StaticResource templateSelector}" /> 

WPF DataGrid Control的更多相关文章

  1. csharp: Data binding in WPF DataGrid control

    <Window x:Class="WpfProjectDemo.MainWindow" xmlns="http://schemas.microsoft.com/wi ...

  2. WPF DataGrid常用属性记录

    WPF DataGrid常用属性记录 组件常用方法: BeginEdit:使DataGrid进入编辑状态. CancelEdit:取消DataGrid的编辑状态. CollapseRowGroup:闭 ...

  3. xceed wpf datagrid

    <!--*********************************************************************************** Extended ...

  4. WPF DataGrid自定义样式

    微软的WPF DataGrid中有很多的属性和样式,你可以调整,以寻找合适的(如果你是一名设计师).下面,找到我的小抄造型的网格.它不是100%全面,但它可以让你走得很远,有一些非常有用的技巧和陷阱. ...

  5. WPF DataGrid显格式

    Guide to WPF DataGrid formatting using bindings Peter Huber SG, 25 Nov 2013 CPOL    4.83 (13 votes) ...

  6. WPF DataGrid Custommization using Style and Template

    WPF DataGrid Custommization using Style and Template 代码下载:http://download.csdn.net/detail/wujicai/81 ...

  7. WPF DATAGRID - COMMITTING CHANGES CELL-BY-CELL

    In my recent codeproject article on the DataGrid I described a number of techniques for handling the ...

  8. Hosting custom WPF calendar control in AX 2012

    原作者: https://community.dynamics.com/ax/b/axilicious/archive/2013/05/20/hosting-custom-wpf-calendar-c ...

  9. Tutorial: WPF User Control for AX2012

    原作者: https://community.dynamics.com/ax/b/goshoom/archive/2011/10/06/tutorial-wpf-user-control-for-ax ...

随机推荐

  1. python基础——偏函数

    python基础——偏函数 Python的functools模块提供了很多有用的功能,其中一个就是偏函数(Partial function).要注意,这里的偏函数和数学意义上的偏函数不一样. 在介绍函 ...

  2. *** Assertion failure in -[UIApplication _runWithMainScene:transitionContext iOS9.1闪退问题解决

    错误原因在于 AppDelegate 中 didFinishLaunchingWithOptions 结束前 未定义 rootViewController,Xcode7规定必须要有rootViewCo ...

  3. Java大数处理类:BigInteger类和BigDecimal类

    当我们要处理非常大的数据时,平常用的数据类型已不足以表示,在Java中有两个类BigInteger和BigDecimal分别表示大整数类和大浮点数类,这两个类在理论上只要计算机内存足够大就能够表示无线 ...

  4. .NET开发工具之Excel导出公共类

    来源:Pino晨 链接:cnblogs.com/chenxygx/p/5954870.html 说明 最近接了一个任务,就是做一个列表的Excel导出功能.并且有很多页面都会使用这个功能. 导出的Ex ...

  5. Dubbo超时和重连机制

    dubbo启动时默认有重试机制和超时机制.超时机制的规则是如果在一定的时间内,provider没有返回,则认为本次调用失败,重试机制在出现调用失败时,会再次调用.如果在配置的调用次数内都失败,则认为此 ...

  6. 【数据库】 Sqlserver 2008 error 40出现连接错误的解决方法

    经常要连接到远程数据库上,因此常常碰到这个错误,然后又屡次忘记解决方法,所以今天坐下笔迹,好下次能快速回忆起来. 一.首先检查数据库的TCP/TP是否启动 1.启动Sql server配置管理器 2. ...

  7. HTML5学习之拖放(十)

    l元素可以用于拖拽必须设置draggable="true"属性,img和a标签除外,她们两个默认就可以被拖拽 想做拖拽处理,就需要在Dom元素上监听拖放的事件:dragstart, ...

  8. node 初识

    跟随startup engineering 已经到了week2了,目前为止课程都没有详细介绍node,恐怕以后也不会讲得太细,只是罗列出了一堆阅读材料供你自学.花了点时间阅读些许,在此做个墨迹. Ho ...

  9. Linux下修改默认字符集--->解决Linux下Java程序种中文文件夹file.isDirectory()判断失败的问题

    一.问题描述: 一个项目中为了生成树状目录,调用了file.listFiles()方法,然后利用file.isDirectory()方法判断是否为目录,该程序在windows下运行无问题,在Linux ...

  10. hibernate查询语句实例代码

    一.聚集函数的使用: avg(...), sum(...), min(...), max(...) count(*) count(...), count(distinct ...), count(al ...