Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

DataGrid Class

Displays data in a customizable grid.

Namespace:  System.Windows.Controls
Assembly:  System.Windows.Controls.Data (in System.Windows.Controls.Data.dll)

[TemplateVisualStateAttribute(Name = "Disabled", GroupName = "CommonStates")]
[TemplateVisualStateAttribute(Name = "Valid", GroupName = "ValidationStates")]
[TemplateVisualStateAttribute(Name = "Invalid", GroupName = "ValidationStates")]
[StyleTypedPropertyAttribute(Property = "ColumnHeaderStyle", StyleTargetType = typeof(DataGridColumnHeader))]
[StyleTypedPropertyAttribute(Property = "RowHeaderStyle", StyleTargetType = typeof(DataGridRowHeader))]
[StyleTypedPropertyAttribute(Property = "RowStyle", StyleTargetType = typeof(DataGridRow))]
[TemplatePartAttribute(Name = "ValidationSummary", Type = typeof(ValidationSummary))]
[StyleTypedPropertyAttribute(Property = "CellStyle", StyleTargetType = typeof(DataGridCell))]
[TemplatePartAttribute(Name = "RowsPresenter", Type = typeof(DataGridRowsPresenter))]
[TemplatePartAttribute(Name = "VerticalScrollbar", Type = typeof(ScrollBar))]
[TemplatePartAttribute(Name = "FrozenColumnScrollBarSpacer", Type = typeof(FrameworkElement))]
[TemplatePartAttribute(Name = "HorizontalScrollbar", Type = typeof(ScrollBar))]
[StyleTypedPropertyAttribute(Property = "DragIndicatorStyle", StyleTargetType = typeof(ContentControl))]
[StyleTypedPropertyAttribute(Property = "DropLocationIndicatorStyle", StyleTargetType = typeof(ContentControl))]
[TemplatePartAttribute(Name = "ColumnHeadersPresenter", Type = typeof(DataGridColumnHeadersPresenter))]
[TemplateVisualStateAttribute(Name = "Normal", GroupName = "CommonStates")]
public class DataGrid : Control
<sdk:DataGrid .../>

The DataGrid type exposes the following members.

  NameDescription
Public methodDataGridInitializes a new instance of the DataGrid class.
Top

  NameDescription
Public propertyActualHeightGets the rendered height of a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyActualWidthGets the rendered width of a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyAllowDropGets or sets a value that determines whether this UIElement can be a drop target for purposes of Silverlight drag-and-drop operations. (Inherited from UIElement.)
Public propertyAlternatingRowBackgroundGets or sets the Brush that is used to paint the background of odd-numbered rows.
Public propertyAreRowDetailsFrozenGets or sets a value that indicates whether the row details sections remain fixed at the width of the display area or can scroll horizontally.
Public propertyAreRowGroupHeadersFrozenGets or sets a value that indicates whether the row group header sections remain fixed at the width of the display area or can scroll horizontally.
Public propertyAutoGenerateColumnsGets or sets a value that indicates whether columns are created automatically when the ItemsSource property is set.
Public propertyBackgroundGets or sets a brush that provides the background of the control. (Inherited from Control.)
Public propertyBorderBrushGets or sets a brush that describes the border background of a control. (Inherited from Control.)
Public propertyBorderThicknessGets or sets the border thickness of a control. (Inherited from Control.)
Public propertyCacheModeGets or sets a value that indicates that rendered content should be cached when possible. (Inherited from UIElement.)
Public propertyCanUserReorderColumnsGets or sets a value that indicates whether the user can change the column display order by dragging column headers with the mouse.
Public propertyCanUserResizeColumnsGets or sets a value that indicates whether the user can adjust column widths using the mouse.
Public propertyCanUserSortColumnsGets or sets a value that indicates whether the user can sort columns by clicking the column header.
Public propertyCellStyleGets or sets the style that is used when rendering the data grid cells.
Public propertyCharacterSpacingGets or sets the distance between characters of text in the control measured in 1000ths of the font size. (Inherited from Control.)
Public propertyClipGets or sets the Geometry used to define the outline of the contents of a UIElement. (Inherited from UIElement.)
Public propertyClipboardCopyModeGets or sets a value that indicates how data is copied to the clipboard.
Public propertyColumnHeaderHeightGets or sets the height of the column headers row.
Public propertyColumnHeaderStyleGets or sets the style that is used when rendering the column headers.
Public propertyColumnsGets a collection that contains all the columns in the control.
Public propertyColumnWidthGets or sets the standard width or automatic sizing mode of columns in the control.
Public propertyCurrentColumnGets or sets the column that contains the current cell.
Protected propertyCurrentItemGets the data item bound to the row that contains the current cell.
Public propertyCursorGets or sets the cursor image that displays while the mouse pointer is over a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyDataContextGets or sets the data context for a FrameworkElement when it participates in data binding. (Inherited from FrameworkElement.)
Protected propertyDefaultStyleKeyGets or sets the key that references the default style for the control. (Inherited from Control.)
Public propertyDesiredSizeGets the size that this UIElement computed during the measure pass of the layout process. (Inherited from UIElement.)
Public propertyDispatcherGets the Dispatcher this object is associated with. (Inherited from DependencyObject.)
Public propertyDragIndicatorStyleGets or sets the style that is used when rendering the drag indicator that is displayed while dragging column headers.
Public propertyDropLocationIndicatorStyleGets or sets the style that is used when rendering the column headers.
Public propertyEffectGets or sets the pixel shader effect to use for rendering this UIElement. (Inherited from UIElement.)
Public propertyFlowDirectionGets or sets the direction that text and other user interface elements flow within any parent element that controls their layout. (Inherited from FrameworkElement.)
Public propertyFontFamilyGets or sets the font used to display text in the control. (Inherited from Control.)
Public propertyFontSizeGets or sets the size of the text in this control. (Inherited from Control.)
Public propertyFontStretchGets or sets the degree to which a font is condensed or expanded on the screen. (Inherited from Control.)
Public propertyFontStyleGets or sets the style in which the text is rendered. (Inherited from Control.)
Public propertyFontWeightGets or sets the thickness of the specified font. (Inherited from Control.)
Public propertyForegroundGets or sets a brush that describes the foreground color. (Inherited from Control.)
Public propertyFrozenColumnCountGets or sets the number of columns that the user cannot scroll horizontally.
Public propertyGridLinesVisibilityGets or sets a value that indicates which grid lines separating inner cells are shown.
Public propertyHeadersVisibilityGets or sets a value that indicates the visibility of row and column headers.
Public propertyHeightGets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyHorizontalAlignmentGets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement.)
Public propertyHorizontalContentAlignmentGets or sets the horizontal alignment of the control's content. (Inherited from Control.)
Public propertyHorizontalGridLinesBrushGets or sets the Brush that is used to paint grid lines separating rows.
Public propertyHorizontalScrollBarVisibilityGets or sets a value that indicates how the horizontal scroll bar is displayed.
Public propertyIsEnabledGets or sets a value indicating whether the user can interact with the control. (Inherited from Control.)
Public propertyIsHitTestVisibleGets or sets whether the contained area of this UIElement can return true values for hit testing. (Inherited from UIElement.)
Public propertyIsReadOnlyGets or sets a value that indicates whether the user can edit the values in the control.
Public propertyIsTabStopGets or sets a value that indicates whether a control is included in tab navigation. (Inherited from Control.)
Public propertyIsValidGets a value that indicates whether data in the grid is valid.
Public propertyItemsSourceGets or sets a collection that is used to generate the content of the control.
Public propertyLanguageGets or sets localization/globalization language information that applies to a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyMarginGets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyMaxColumnWidthGets or sets the maximum width of columns in the DataGrid.
Public propertyMaxHeightGets or sets the maximum height constraint of a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyMaxWidthGets or sets the maximum width constraint of a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyMinColumnWidthGets or sets the minimum width of columns in the DataGrid.
Public propertyMinHeightGets or sets the minimum height constraint of a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyMinWidthGets or sets the minimum width constraint of a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyNameGets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement.)
Public propertyOpacityGets or sets the degree of the object's opacity. (Inherited from UIElement.)
Public propertyOpacityMaskGets or sets the brush used to alter the opacity of regions of this object. (Inherited from UIElement.)
Public propertyPaddingGets or sets the padding inside a control. (Inherited from Control.)
Public propertyParentGets the parent object of this FrameworkElement in the object tree. (Inherited from FrameworkElement.)
Public propertyProjectionGets or sets the perspective projection (3-D effect) to apply when rendering this UIElement. (Inherited from UIElement.)
Public propertyRenderSizeGets the final render size of a UIElement. (Inherited from UIElement.)
Public propertyRenderTransformGets or sets transform information that affects the rendering position of a UIElement. (Inherited from UIElement.)
Public propertyRenderTransformOriginGets or sets the origin point of any possible render transform declared by RenderTransform, relative to the bounds of the UIElement. (Inherited from UIElement.)
Public propertyResourcesGets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement.Resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement.)
Public propertyRowBackgroundGets or sets the Brush that is used to paint row backgrounds.
Public propertyRowDetailsTemplateGets or sets the template that is used to display the content of the details section of rows.
Public propertyRowDetailsVisibilityModeGets or sets a value that indicates when the details sections of rows are displayed.
Public propertyRowGroupHeaderStylesGets the style that is used when rendering the row group header.
Public propertyRowHeaderStyleGets or sets the style that is used when rendering the row headers.
Public propertyRowHeaderWidthGets or sets the width of the row header column.
Public propertyRowHeightGets or sets the standard height of rows in the control.
Public propertyRowStyleGets or sets the style that is used when rendering the rows.
Public propertySelectedIndexGets or sets the index of the current selection.
Public propertySelectedItemGets or sets the data item corresponding to the selected row.
Public propertySelectedItemsGets a list that contains the data items corresponding to the selected rows.
Public propertySelectionModeGets or sets the selection behavior of the data grid.
Public propertyStyleGets or sets an instance Style that is applied for this object during rendering. (Inherited from FrameworkElement.)
Public propertyTabIndexGets or sets a value that determines the order in which elements receive focus when the user navigates through controls by using the TAB key. (Inherited from Control.)
Public propertyTabNavigationGets or sets a value that modifies how tabbing and TabIndex work for this control. (Inherited from Control.)
Public propertyTagGets or sets an arbitrary object value that can be used to store custom information about this object. (Inherited from FrameworkElement.)
Public propertyTemplateGets or sets a control template. (Inherited from Control.)
Public propertyTriggersGets the collection of triggers for animations that are defined for a FrameworkElement. (Inherited from FrameworkElement.)
Public propertyUseLayoutRoundingGets or sets a value that determines whether rendering for the object and its visual subtree should use rounding behavior that aligns rendering to whole pixels. (Inherited from UIElement.)
Public propertyVerticalAlignmentGets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement.)
Public propertyVerticalContentAlignmentGets or sets the vertical alignment of the control's content. (Inherited from Control.)
Public propertyVerticalGridLinesBrushGets or sets the Brush that is used to paint grid lines separating columns.
Public propertyVerticalScrollBarVisibilityGets or sets a value that indicates how the vertical scroll bar is displayed.
Public propertyVisibilityGets or sets the visibility of a UIElement. A UIElement that is not visible does not render and does not communicate its desired size to layout. (Inherited from UIElement.)
Public propertyWidthGets or sets the width of a FrameworkElement. (Inherited from FrameworkElement.)
Top

  NameDescription
Public methodAddHandlerAdds a routed event handler for a specified routed event, adding the handler to the handler collection on the current element. Specify handledEventsToo as true to have the provided handler be invoked for routed event that had already been marked as handled by another element along the event route. (Inherited from UIElement.)
Public methodApplyTemplateLoads the relevant control template so that its parts can be referenced. (Inherited from Control.)
Public methodArrangePositions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement.)
Protected methodArrangeOverrideArranges the content of the DataGrid. (Overrides FrameworkElement.ArrangeOverride(Size).)
Public methodBeginEdit()Causes the data grid to enter editing mode for the current cell and current row, unless the data grid is already in editing mode.
Public methodBeginEdit(RoutedEventArgs)Causes the data grid to enter editing mode for the current cell and current row in the specified keyboard and mouse state.
Public methodCancelEdit()Causes the data grid to cancel the current edit, restore the original value, and exit editing mode.
Public methodCancelEdit(DataGridEditingUnit)Causes the data grid to cancel the current edit, restore the original value, and exit editing mode.
Public methodCaptureMouseSets mouse capture to a UIElement. (Inherited from UIElement.)
Public methodCheckAccessDetermines whether the calling thread has access to this object. (Inherited from DependencyObject.)
Public methodClearValueClears the local value of a dependency property. (Inherited from DependencyObject.)
Public methodCollapseRowGroupCollapses data grid row groups.
Public methodCommitEdit()Causes the data grid to commit the current edit to the data source and exit editing mode.
Public methodCommitEdit(DataGridEditingUnit, Boolean)Causes the data grid to commit the current edit to the data source, and optionally exit editing mode.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Public methodExpandRowGroupExpands data grid row groups.
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodFindNameRetrieves an object that has the specified identifier name. (Inherited from FrameworkElement.)
Public methodFocusAttempts to set the focus on the control. (Inherited from Control.)
Public methodGetAnimationBaseValueReturns any base value established for a Silverlight dependency property, which would apply in cases where an animation is not active. (Inherited from DependencyObject.)
Public methodGetBindingExpressionRetrieves the BindingExpression for a dependency property where a binding is established. (Inherited from FrameworkElement.)
Public methodGetGroupFromItemGets the row group that the specified item belongs to.
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Protected methodGetTemplateChildRetrieves the named element in the instantiated ControlTemplate visual tree. (Inherited from Control.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetValueReturns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject.)
Public methodInvalidateArrangeInvalidates the arrange state (layout) for a UIElement. After the invalidation, the UIElement will have its layout updated, which will occur asynchronously. (Inherited from UIElement.)
Public methodInvalidateMeasureInvalidates the measurement state (layout) for a UIElement. (Inherited from UIElement.)
Public methodMeasureUpdates the DesiredSize of a UIElement. Typically, objects that implement custom layout for their layout children call this method from their own MeasureOverride implementations to form a recursive layout update. (Inherited from UIElement.)
Protected methodMeasureOverrideMeasures the children of a DataGrid in preparation of arranging them during the ArrangeOverride pass. (Overrides FrameworkElement.MeasureOverride(Size).)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodOnApplyTemplateBuilds the visual tree for the DataGrid control when a new template is applied. (Overrides FrameworkElement.OnApplyTemplate().)
Protected methodOnAutoGeneratingColumnRaises the AutoGeneratingColumn event.
Protected methodOnBeginningEditRaises the BeginningEdit event.
Protected methodOnCellEditEndedRaises the CellEditEnded event.
Protected methodOnCellEditEndingRaises the CellEditEnding event.
Protected methodOnColumnDisplayIndexChangedRaises the ColumnDisplayIndexChanged event.
Protected methodOnColumnReorderedRaises the ColumnReordered event.
Protected methodOnColumnReorderingRaises the ColumnReordering event.
Protected methodOnCopyingRowClipboardContentRaises the CopyingRowClipboardContent event.
Protected methodOnCreateAutomationPeerReturns a DataGridAutomationPeer for use by the Silverlight automation infrastructure. (Overrides UIElement.OnCreateAutomationPeer().)
Protected methodOnCurrentCellChangedRaises the CurrentCellChanged event.
Protected methodOnDragEnterCalled before the DragEnter event occurs. (Inherited from Control.)
Protected methodOnDragLeaveCalled before the DragLeave event occurs. (Inherited from Control.)
Protected methodOnDragOverCalled before the DragOver event occurs. (Inherited from Control.)
Protected methodOnDropCalled before the Drop event occurs. (Inherited from Control.)
Protected methodOnGotFocusCalled before the GotFocus event occurs. (Inherited from Control.)
Protected methodOnKeyDownCalled before the KeyDown event occurs. (Inherited from Control.)
Protected methodOnKeyUpCalled before the KeyUp event occurs. (Inherited from Control.)
Protected methodOnLoadingRowRaises the LoadingRow event.
Protected methodOnLoadingRowDetailsRaises the LoadingRowDetails event.
Protected methodOnLoadingRowGroupRaises the LoadingRowGroup event.
Protected methodOnLostFocusCalled before the LostFocus event occurs. (Inherited from Control.)
Protected methodOnLostMouseCaptureCalled before the LostMouseCapture event occurs to provide handling for the event in a derived class without attaching a delegate. (Inherited from Control.)
Protected methodOnMouseEnterCalled before the MouseEnter event occurs. (Inherited from Control.)
Protected methodOnMouseLeaveCalled before the MouseLeave event occurs. (Inherited from Control.)
Protected methodOnMouseLeftButtonDownCalled before the MouseLeftButtonDown event occurs. (Inherited from Control.)
Protected methodOnMouseLeftButtonUpCalled before the MouseLeftButtonUp event occurs. (Inherited from Control.)
Protected methodOnMouseMoveCalled before the MouseMove event occurs. (Inherited from Control.)
Protected methodOnMouseRightButtonDownCalled before the MouseRightButtonDown event occurs. (Inherited from Control.)
Protected methodOnMouseRightButtonUpCalled before the MouseRightButtonUp event occurs. (Inherited from Control.)
Protected methodOnMouseWheelProvides handling for the MouseWheel event. (Overrides Control.OnMouseWheel(MouseWheelEventArgs).)
Protected methodOnPreparingCellForEditRaises the PreparingCellForEdit event.
Protected methodOnRowDetailsVisibilityChangedRaises the RowDetailsVisibilityChanged event.
Protected methodOnRowEditEndedRaises the RowEditEnded event.
Protected methodOnRowEditEndingRaises the RowEditEnding event.
Protected methodOnSelectionChangedRaises the SelectionChanged event.
Protected methodOnTextInputCalled before the TextInput event occurs. (Inherited from Control.)
Protected methodOnTextInputStartCalled before the TextInputStart event occurs. (Inherited from Control.)
Protected methodOnTextInputUpdateCalled before the TextInputUpdate event occurs. (Inherited from Control.)
Protected methodOnUnloadingRowRaises the UnloadingRow event.
Protected methodOnUnloadingRowDetailsRaises the UnloadingRowDetails event.
Protected methodOnUnloadingRowGroupRaises the UnloadingRowGroup event.
Public methodReadLocalValueReturns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject.)
Public methodReleaseMouseCaptureRemoves mouse capture from a UIElement. After this call, typically no object holds mouse capture. (Inherited from UIElement.)
Public methodRemoveHandlerRemoves the specified routed event handler from this UIElement. (Inherited from UIElement.)
Public methodScrollIntoViewScrolls the DataGrid vertically to display the row for the specified data item and scrolls the DataGrid horizontally to display the specified column.
Public methodSetBindingAttaches a binding to a FrameworkElement, using the provided binding object, and returns a BindingExpressionBase for possible later use. (Inherited from FrameworkElement.)
Public methodSetValueSets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodTransformToVisualReturns a transform object that can be used to transform coordinates from the UIElement to the specified object. (Inherited from UIElement.)
Public methodUpdateLayoutEnsures that all positions of child objects of a UIElement are properly updated for layout. (Inherited from UIElement.)
Top

  NameDescription
Public eventAutoGeneratingColumnOccurs one time for each public, non-static property in the bound data type when the ItemsSource property is changed and the AutoGenerateColumns property is true.
Public eventBeginningEditOccurs before a cell or row enters editing mode.
Public eventBindingValidationErrorOccurs when a data validation error is reported by a binding source. (Inherited from FrameworkElement.)
Public eventCellEditEndedOccurs when a cell edit has been committed or canceled.
Public eventCellEditEndingOccurs when a cell edit is ending.
Public eventColumnDisplayIndexChangedOccurs when the DisplayIndex property of a column changes.
Public eventColumnHeaderDragCompletedOccurs when the user drops a column header that was being dragged using the mouse.
Public eventColumnHeaderDragDeltaOccurs one or more times while the user drags a column header using the mouse.
Public eventColumnHeaderDragStartedOccurs when the user begins dragging a column header using the mouse.
Public eventColumnReorderedOccurs when a DataGrid column has moved to a new position in the display order.
Public eventColumnReorderingOccurs before a DataGrid column moves to a new position in the display order.
Public eventCopyingRowClipboardContentOccurs when the row is prepared for a clipboard copy operation.
Public eventCurrentCellChangedOccurs when a different cell becomes the current cell.
Public eventDataContextChangedOccurs when the data context for this element changes. (Inherited from FrameworkElement.)
Public eventDragEnterOccurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement.)
Public eventDragLeaveOccurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement.)
Public eventDragOverOccurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement.)
Public eventDropOccurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement.)
Public eventGotFocusOccurs when a UIElement receives focus. (Inherited from UIElement.)
Public eventIsEnabledChangedOccurs when the IsEnabled property changes. (Inherited from Control.)
Public eventKeyDownOccurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement.)
Public eventKeyUpOccurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement.)
Public eventLayoutUpdatedOccurs when the layout of the Silverlight visual tree changes. (Inherited from FrameworkElement.)
Public eventLoadedOccurs when a FrameworkElement has been constructed and added to the object tree. (Inherited from FrameworkElement.)
Public eventLoadingRowOccurs after a DataGridRow is instantiated, so that you can customize it before it is used.
Public eventLoadingRowDetailsOccurs when a new row details template is applied to a row, so that you can customize the details section before it is used.
Public eventLoadingRowGroupOccurs when a row group header is loading, so that you can customize the header before it is used.
Public eventLostFocusOccurs when a UIElement loses focus. (Inherited from UIElement.)
Public eventLostMouseCaptureOccurs when the UIElement loses mouse capture. (Inherited from UIElement.)
Public eventMediaCommandOccurs when a button is pressed on a remote control. (Inherited from UIElement.)
Public eventMouseEnterOccurs when the mouse (or a stylus) enters the bounding area of a UIElement. (Inherited from UIElement.)
Public eventMouseLeaveOccurs when the mouse (or the stylus) leaves the bounding area of a UIElement. (Inherited from UIElement.)
Public eventMouseLeftButtonDownOccurs when the left mouse button is pressed (or when the tip of the stylus touches the tablet) while the mouse pointer is over a UIElement. (Inherited from UIElement.)
Public eventMouseLeftButtonUpOccurs when the left mouse button is released (or the tip of the stylus is removed from the tablet) while the mouse (or the stylus) is over a UIElement (or while a UIElement holds mouse capture). (Inherited from UIElement.)
Public eventMouseMoveOccurs when the coordinate position of the mouse (or stylus) changes while over a UIElement (or while a UIElement holds mouse capture). (Inherited from UIElement.)
Public eventMouseRightButtonDownOccurs when the right mouse button is pressed while the mouse pointer is over a UIElement. (Inherited from UIElement.)
Public eventMouseRightButtonUpOccurs when the right mouse button is released while the mouse pointer is over a UIElement. However, this event will only be raised if a caller marks the preceding MouseRightButtonDown event as handled; see Remarks. (Inherited from UIElement.)
Public eventMouseWheelOccurs when the user rotates the mouse wheel while the mouse pointer is over a UIElement, or the UIElement has focus. (Inherited from UIElement.)
Public eventPreparingCellForEditOccurs when a cell in a DataGridTemplateColumn enters editing mode.
Public eventRowDetailsVisibilityChangedOccurs when the RowDetailsVisibilityMode property value changes.
Public eventRowEditEndedOccurs when a row edit has been committed or canceled.
Public eventRowEditEndingOccurs when a row edit is ending.
Public eventSelectionChangedOccurs when the SelectedItem or SelectedItems property value changes.
Public eventSizeChangedOccurs when either the ActualHeight or the ActualWidth properties change value on a FrameworkElement. (Inherited from FrameworkElement.)
Public eventTextInputOccurs when a UI element gets text in a device-independent manner. (Inherited from UIElement.)
Public eventTextInputStartOccurs when a UI element initially gets text in a device-independent manner. (Inherited from UIElement.)
Public eventTextInputUpdateOccurs when text continues to be composed via an input method editor (IME). (Inherited from UIElement.)
Public eventUnloadedOccurs when this object is no longer connected to the main object tree. (Inherited from FrameworkElement.)
Public eventUnloadingRowOccurs when a DataGridRow object becomes available for reuse.
Public eventUnloadingRowDetailsOccurs when a row details element becomes available for reuse.
Public eventUnloadingRowGroupOccurs when a row group is unloading.
Top

  NameDescription
Public fieldStatic memberAlternatingRowBackgroundPropertyIdentifies the AlternatingRowBackground dependency property.
Public fieldStatic memberAreRowDetailsFrozenPropertyIdentifies the AreRowDetailsFrozen dependency property.
Public fieldStatic memberAreRowGroupHeadersFrozenPropertyIdentifies the AreRowGroupHeadersFrozen dependency property.
Public fieldStatic memberAutoGenerateColumnsPropertyIdentifies the AutoGenerateColumns dependency property.
Public fieldStatic memberCanUserReorderColumnsPropertyIdentifies the CanUserReorderColumns dependency property.
Public fieldStatic memberCanUserResizeColumnsPropertyIdentifies the CanUserResizeColumns dependency property.
Public fieldStatic memberCanUserSortColumnsPropertyIdentifies the CanUserSortColumns dependency property.
Public fieldStatic memberCellStylePropertyIdentifies the CellStyle dependency property.
Public fieldStatic memberClipboardCopyModePropertyIdentifies the ClipboardCopyMode dependency property.
Public fieldStatic memberColumnHeaderHeightPropertyIdentifies the ColumnHeaderHeight dependency property.
Public fieldStatic memberColumnHeaderStylePropertyIdentifies the ColumnHeaderStyle dependency property.
Public fieldStatic memberColumnWidthPropertyIdentifies the ColumnWidth dependency property.
Public fieldStatic memberDragIndicatorStylePropertyIdentifies the DragIndicatorStyle dependency property.
Public fieldStatic memberDropLocationIndicatorStylePropertyIdentifies the DropLocationIndicatorStyle dependency property.
Public fieldStatic memberFrozenColumnCountPropertyIdentifies the FrozenColumnCount dependency property.
Public fieldStatic memberGridLinesVisibilityPropertyIdentifies the GridLinesVisibility dependency property.
Public fieldStatic memberHeadersVisibilityPropertyIdentifies the HeadersVisibility dependency property.
Public fieldStatic memberHorizontalGridLinesBrushPropertyIdentifies the HorizontalGridLinesBrush dependency property.
Public fieldStatic memberHorizontalScrollBarVisibilityPropertyIdentifies the HorizontalScrollBarVisibility dependency property.
Public fieldStatic memberIsReadOnlyPropertyIdentifies the IsReadOnly dependency property.
Public fieldStatic memberIsValidPropertyIdentifies the IsValid dependency property.
Public fieldStatic memberItemsSourcePropertyIdentifies the ItemsSource dependency property.
Public fieldStatic memberMaxColumnWidthPropertyIdentifies the MaxColumnWidth dependency property.
Public fieldStatic memberMinColumnWidthPropertyIdentifies the MinColumnWidth dependency property.
Public fieldStatic memberRowBackgroundPropertyIdentifies the RowBackground dependency property.
Public fieldStatic memberRowDetailsTemplatePropertyIdentifies the RowDetailsTemplate dependency property.
Public fieldStatic memberRowDetailsVisibilityModePropertyIdentifies the RowDetailsVisibilityMode dependency property.
Public fieldStatic memberRowHeaderStylePropertyIdentifies the RowHeaderStyle dependency property.
Public fieldStatic memberRowHeaderWidthPropertyIdentifies the RowHeaderWidth dependency property.
Public fieldStatic memberRowHeightPropertyIdentifies the RowHeight dependency property.
Public fieldStatic memberRowStylePropertyIdentifies the RowStyle dependency property.
Public fieldStatic memberSelectedIndexPropertyIdentifies the SelectedIndex dependency property.
Public fieldStatic memberSelectedItemPropertyIdentifies the SelectedItem dependency property.
Public fieldStatic memberSelectionModePropertyIdentifies the SelectionMode dependency property.
Public fieldStatic memberVerticalGridLinesBrushPropertyIdentifies the VerticalGridLinesBrush dependency property.
Public fieldStatic memberVerticalScrollBarVisibilityPropertyIdentifies the VerticalScrollBarVisibility dependency property.
Top

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.

The following illustration shows an example of a DataGrid.

DataGrid control example

For information about adding and referencing a DataGrid control, see How to: Add a DataGrid Control to a Page.

NoteNote:

The DataGrid control is available as part of the libraries in the Silverlight Software Development Kit (SDK). For more information, see the Silverlight Tools.

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<T>. In order to automatically reflect property changes, the objects in the source collection must implement the INotifyPropertyChanged interface.

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.

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.

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.

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.

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.

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.

NoteNote:

Setting a visual property will only have an effect if that property is both present in DataGrid control's default template and is set by using a TemplateBinding Markup Extension. You can find a list of visual properties in the "Changing the Visual Structure of a Control" section of Customizing the Appearance of an Existing Control by Using a ControlTemplate.

The following code example creates a page with several DataGrid controls configured in a variety of ways.

Run this sample


<!-- 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>



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)
            });
        }
    }
}


Silverlight

Supported in: 5, 4, 3

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

Show:
© 2014 Microsoft