[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]
Represents a control that displays data in a customizable grid.
Namespace:
System.Windows.Controls
Assembly:
PresentationFramework (in PresentationFramework.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation, http://schemas.microsoft.com/netfx/2007/xaml/presentation
'Usage
Dim instance As DataGrid
'Declaration
Public Class DataGrid _
Inherits MultiSelector
<DataGrid>
Items
</DataGrid>
Use the DataGrid control to display data in a grid of rows and columns. Specify the data source by setting the ItemsSource property directly or with a binding. For more information, see Data Binding. By default, DataGrid will auto-generate columns based on the data source. The following table lists the generated columns types.
The following illustration shows each of the column types.
.png)
You can turn off auto-generation of columns by setting the AutoGenerateColumns property to false. Then you can create your own set of Columns by using the existing column types or you can create a new column type with DataGridTemplateColumn. Each column defined in the Columns collection creates a column in the DataGrid.
DataGrid supports many ways to customize the data display. The following table lists common scenarios.
Scenario | Approach |
|---|
Alternating background colors | Set the AlternationIndex property to 2 or more, and then assign a Brush to the RowBackground and AlternatingRowBackground properties. |
Define cell and row selection behavior | Set the SelectionMode and SelectionUnit properties. |
Customize the visual appearance of headers, cells and rows | Apply a new Style to the ColumnHeaderStyle, RowHeaderStyle, CellStyle, or RowStyle properties. |
Access selected items | Check the SelectedCells property to get the selected cells and check the SelectedItems property to get the selected rows. For more information, see the SelectedCells property. |
Customize end-user interactions | Set the CanUserAddRows, CanUserDeleteRows, CanUserReorderColumns, CanUserResizeColumns, CanUserResizeRows, and CanUserSortColumns properties. |
Cancel or change auto-generated columns | Handle the AutoGeneratingColumn event. |
Freeze a column | Set the FrozenColumnCount property to 1 and move the column to the left-most position by setting the DisplayIndex property to 0. |
Use XML data as the data source | Bind the ItemsSource on the DataGrid to the XPath query representing the collection of items. Create each column in the DataGrid. Bind each column by setting the XPath on the binding to the query that gets the property on the item source. For an example, see DataGridTextColumn. |
The following example shows how to bind a DataGrid to a DataTable and use column auto-generation. The DataTable was populated by using the Fill method of a DataAdapter from a DataSet. For more information, see Creating a DataSet (ADO.NET) and Populating a DataSet from a DataAdapter (ADO.NET). To use the WPF Designer for Visual Studio, see How to: Bind WPF Controls to Data in Visual Studio.
<DataGrid x:Name="CustomerGrid" ItemsSource="{Binding}" AlternatingRowBackground="LightBlue" AlternationCount="2" />
'Set the DataGrid's DataContext to be a filled DataTable
CustomerGrid.DataContext = custDataTable
The following example shows how to create a DataGrid with a customized Columns collection.
<NavigationWindow x:Class="DataGrid_CustomColumns.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:core="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:DataGrid_CustomColumns"
Title="Customers" Height="300" Width="300" ShowsNavigationUI="False" >
<NavigationWindow.Resources>
<!--Create list of enumeration values-->
<ObjectDataProvider x:Key="myEnum" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:OrderStatus"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<!--Create an instance of the converter for Email-->
<local:EmailConverter x:Key="EmailConverter" />
</NavigationWindow.Resources>
<NavigationWindow.Content>
<Grid>
<DataGrid Name="DG1" ItemsSource="{Binding}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" />
<!--The Email property contains a URI. For example "mailto:lucy0@adventure-works.com"-->
<DataGridHyperlinkColumn Header="Email" Binding="{Binding Email}" ContentBinding="{Binding Email, Converter={StaticResource EmailConverter}}" />
<DataGridCheckBoxColumn Header="Member?" Binding="{Binding IsMember}" />
<DataGridComboBoxColumn Header="Order Status" SelectedItemBinding="{Binding Status}" ItemsSource="{Binding Source={StaticResource myEnum}}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</NavigationWindow.Content>
</NavigationWindow>
'Additional using statements
Imports System.Data
Imports System.Collections.ObjectModel
Imports System.Diagnostics
...
Class Window1
...
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
'GetData() creates a collection of Customer data from a database
Dim custdata As ObservableCollection(Of Customer) = GetData()
'Bind the DataGrid to the customer data
DG1.DataContext = custdata
End Sub
...
'Defines the customer object
Public Class Customer
Private _FirstName As String
Public Property FirstName() As String
Get
Return _FirstName
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
Private _LastName As String
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
Private _Email As Uri
Public Property Email() As Uri
Get
Return _Email
End Get
Set(ByVal value As Uri)
_Email = value
End Set
End Property
Private _IsMember As Boolean
Public Property IsMember() As Boolean
Get
Return _IsMember
End Get
Set(ByVal value As Boolean)
_IsMember = value
End Set
End Property
Private _Status As OrderStatus
Public Property Status() As OrderStatus
Get
Return _Status
End Get
Set(ByVal value As OrderStatus)
_Status = value
End Set
End Property
End Class
...
End Class
...
Public Enum OrderStatus
None
[New]
Processing
Shipped
Received
End Enum
...
'Converts the mailto uri to a string with just the customer alias
Public Class EmailConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If value IsNot Nothing Then
Dim email As String = value.ToString()
Dim index As Integer = email.IndexOf("@")
Dim [alias] As String = email.Substring(7, index - 7)
Return [alias]
Else
Dim email As String = ""
Return email
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Dim email As New Uri(DirectCast(value, String))
Return email
End Function
End Class
System..::.Object
System.Windows.Threading..::.DispatcherObject
System.Windows..::.DependencyObject
System.Windows.Media..::.Visual
System.Windows..::.UIElement
System.Windows..::.FrameworkElement
System.Windows.Controls..::.Control
System.Windows.Controls..::.ItemsControl
System.Windows.Controls.Primitives..::.Selector
System.Windows.Controls.Primitives..::.MultiSelector
System.Windows.Controls..::.DataGrid
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008, Windows Server 2003
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
.NET Framework
Supported in: 4
.NET Framework Client Profile
Supported in: 4
Reference
Other Resources