Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The DataGrid control enables you to display and edit data from many different sources, such as from a SQL database, LINQ query, or any other bindable data source. For more information, see Binding Sources Overview.
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.
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 the INotifyCollectionChanged interface, such as an ObservableCollection<T>. To automatically reflect property changes, the objects in the source collection must implement the INotifyPropertyChanged interface. For more information, see Data Binding Overview.
Columns can display text, controls, such as a ComboBox, or any other WPF content, such as images, buttons, or any content contained in a template. You can use a DataGridTemplateColumn to display data defined in a template. The following table lists the column types that are provided by default.
| Generated Column Type | Data Type |
|---|---|
| DataGridTextColumn | String |
| DataGridCheckBoxColumn | Boolean |
| DataGridComboBoxColumn | Enum |
| DataGridHyperlinkColumn | Uri |
Auto-generating columns
By default, the DataGrid control generates columns automatically when you set the ItemsSource property. The type of column that is generated depends on the type of data in the column, as shown in the preceding table.
When columns are auto-generated, you can handle the AutoGeneratingColumn event to customize or cancel columns before they're added to the DataGrid. If you add both user-defined columns and auto-generated columns to the DataGrid, the user-defined columns are added first. To rearrange the display order of the columns, you can set the DisplayIndex property for individual columns.
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.
Custom columns
Use the DataGridTemplateColumn type to define a custom column if the built-in column types don't meet your needs. The DataGridTemplateColumn type provides CellTemplate and CellEditingTemplate properties that enable you to specify content templates for both display and editing modes. For example, you could define a custom column for dates. The CellTemplate could define a TextBlock to display a date, and the CellEditingTemplate could define a DatePicker control to edit the date.
You can use the Columns collection to programmatically add, insert, remove, and change any columns in the control at run time. Check the IsAutoGenerated property to determine whether a column is auto generated or user defined. Auto-generated columns are automatically added, removed, or regenerated when the ItemsSource changes.
DataGrid can be customized in appearance, such as cell font, color, and size. DataGrid supports all styling and templating functionality of other WPF controls. DataGrid also includes default and customizable behaviors for editing, sorting, and validation.
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.
The DataGrid has built-in support for the following editing commands:
| Command | Default Key |
|---|---|
| BeginEditCommand | F2 |
| CancelEditCommand | ESC |
| CommitEditCommand | ENTER |
| DeleteCommand | DELETE |
You put the current cell into edit mode by clicking it or pressing F2. A cell-level edit is committed when you move to another cell in the same row or press ENTER while the cell is in edit mode. All edits in a row are committed when you move to another row or press ENTER while the row is in edit mode. 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 BeginEdit, CommitEdit, and CancelEdit methods.
Set the CanUserAddRows and CanUserDeleteRows properties to specify whether a user can add or delete rows. A user can delete selected rows by pressing the DELETE key. If the CanUserAddRows property is set to true, a new item row is added as the last row in the DataGrid. You can set default values for new items by handling the InitializingNewItem event.
Note
Whether editing actions are allowed is influenced by many factors, including the IsReadOnly and IsEnabled state of the DataGrid, and whether the underlying data collection allows the action.
Selection
By default, the entire row is selected when a user clicks a cell in a DataGrid, and a user can select multiple rows. You can set the SelectionUnit property to specify whether a user can select cells, full rows, or both. Set the SelectionMode property to specify whether multiple rows or cells can be selected, or only single rows or cells.
You can get information about the cells that are selected from the SelectedCells property. You can get information about cells for which selection has changed in the SelectedCellsChangedEventArgs of the SelectedCellsChanged event. Call the SelectAllCells or UnselectAllCells methods to programmatically select or unselect all cells. For more information, see Default Keyboard and Mouse Behavior in the DataGrid Control.
Grouping, sorting, and filtering
By default, you can sort items in a DataGrid by clicking the column header. You can customize sorting by handling the Sorting event. To cancel the default sort, set the Handled property to true. You can also sort the source data before it's displayed in the DataGrid.
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 items are grouped in the DataGrid, you can define a GroupStyle that specifies the appearance of each group. You apply the GroupStyle by adding it to the GroupStyle collection of the DataGrid. If you have multiple levels of grouping, you can apply different styles to each group level. Styles are applied in the order in which they're defined. For more information, see How to: Group, Sort, and Filter Data in the DataGrid Control.
Validation
The DataGrid enables you to perform validation at both the cell and row level. With cell-level validation, you validate individual properties of a bound data object when a user updates a value. With row-level validation, you validate entire data objects when a user commits changes to a row. You can provide customized visual feedback for row-level validation errors by setting the RowValidationErrorTemplate property, or you can use the default error indicator. To create a custom validation rule, create a class that derives from the ValidationRule class and implement the Validate method. Add the custom validation rule to the RowValidationRules collection.
Common tasks
The following table lists some of the common tasks for DataGrid and how to accomplish them. By viewing the related API, you can find more information and sample code.
| Scenario | Approach |
|---|---|
| Alternating background colors | Set the AlternationCount 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. |
| Set sizing options | Set the Height, MaxHeight, MinHeight, Width, MaxWidth, or MinWidth properties. For more information, see Sizing Options in the DataGrid Control. |
| Access selected items | Check the SelectedCells property to get the selected cells and the SelectedItems property to get the selected rows. For more information, see SelectedCells. |
| 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 that represents 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. |
Related articles
| Title | Description |
|---|---|
| DataGrid Elements | Describes the element types that make up the DataGrid, including DataGridCell, DataGridRow, DataGridRowHeader, DataGridColumnHeader, and DataGridColumnHeadersPresenter. |
| Walkthrough: Display Data from a SQL Server Database in a DataGrid Control | Describes how to set up a new WPF project, add an Entity Framework Element, set the source, and display the data in a DataGrid. |
| How to: Add Row Details to a DataGrid Control | Describes how to create row details for a DataGrid. |
| How to: Implement Validation with the DataGrid Control | Describes how to validate values in DataGrid cells and rows, and display validation feedback. |
| Default Keyboard and Mouse Behavior in the DataGrid Control | Describes how to interact with the DataGrid control by using the keyboard and mouse. |
| How to: Group, Sort, and Filter Data in the DataGrid Control | Describes how to view data in a DataGrid in different ways by grouping, sorting, and filtering the data. |
| Sizing Options in the DataGrid Control | Describes how to control absolute and automatic sizing in the DataGrid. |
Customizing the DataGrid
The DataGrid control supports common table formatting options, such as alternating row backgrounds and the ability to show or hide headers, gridlines, 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 reordering. The DataGrid also exposes several events for row recycling that you can handle to customize rows.
To apply the same property settings to multiple DataGrid controls, use the Style property. You can modify the default ControlTemplate to give the control a unique appearance. For more information about creating a ControlTemplate, see Creating a template for a control.
Dependency properties for this control might be set by the control's default style. If a property is set by a default style, the property might change from its default value when the control appears in the application. The default style is determined by which desktop theme is used when the application is running.
Note
Setting a visual property only has an effect if that property is both present in the control's default template and set by using a TemplateBinding.
Styles and templates
This section describes the styles and templates for the DataGrid control. You can modify the default ControlTemplate to give the control a unique appearance. For more information, see Styling and Templating and Creating a template for a control.
Content property
The DataGrid control uses the ItemsSource property to define the data source. The data source can be any bindable collection, such as a database, LINQ query, or other bindable data source.
Parts
This control doesn't define any template parts.
Visual states
The following table lists the visual states for the DataGrid control.
| VisualState Name | VisualStateGroup Name | Description |
|---|---|---|
| Normal | CommonStates | The control is in its normal state. |
| Disabled | CommonStates | The control is disabled. |
| Valid | ValidationStates | The control is valid and has no validation errors. |
| InvalidFocused | ValidationStates | The control has a validation error and has keyboard focus. |
| InvalidUnfocused | ValidationStates | The control has a validation error but does not have keyboard focus. |
DataGrid element types
The DataGrid control is composed of several element types. For information about these elements and their styles and templates, see DataGrid Elements.
See also
.NET Desktop feedback