Поделиться через


DataGrid Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Displays data in a customizable grid.

Inheritance Hierarchy

System.Object
  System.Windows.DependencyObject
    System.Windows.UIElement
      System.Windows.FrameworkElement
        System.Windows.Controls.Control
          System.Windows.Controls.DataGrid

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

Syntax

'Declaration
<TemplateVisualStateAttribute(Name := "Disabled", GroupName := "CommonStates")> _
<TemplateVisualStateAttribute(Name := "Valid", GroupName := "ValidationStates")> _
<TemplateVisualStateAttribute(Name := "Invalid", GroupName := "ValidationStates")> _
<StyleTypedPropertyAttribute(Property := "ColumnHeaderStyle", StyleTargetType := GetType(DataGridColumnHeader))> _
<StyleTypedPropertyAttribute(Property := "RowHeaderStyle", StyleTargetType := GetType(DataGridRowHeader))> _
<StyleTypedPropertyAttribute(Property := "RowStyle", StyleTargetType := GetType(DataGridRow))> _
<TemplatePartAttribute(Name := "ValidationSummary", Type := GetType(ValidationSummary))> _
<StyleTypedPropertyAttribute(Property := "CellStyle", StyleTargetType := GetType(DataGridCell))> _
<TemplatePartAttribute(Name := "RowsPresenter", Type := GetType(DataGridRowsPresenter))> _
<TemplatePartAttribute(Name := "VerticalScrollbar", Type := GetType(ScrollBar))> _
<TemplatePartAttribute(Name := "FrozenColumnScrollBarSpacer", Type := GetType(FrameworkElement))> _
<TemplatePartAttribute(Name := "HorizontalScrollbar", Type := GetType(ScrollBar))> _
<StyleTypedPropertyAttribute(Property := "DragIndicatorStyle", StyleTargetType := GetType(ContentControl))> _
<StyleTypedPropertyAttribute(Property := "DropLocationIndicatorStyle", StyleTargetType := GetType(ContentControl))> _
<TemplatePartAttribute(Name := "ColumnHeadersPresenter", Type := GetType(DataGridColumnHeadersPresenter))> _
<TemplateVisualStateAttribute(Name := "Normal", GroupName := "CommonStates")> _
Public Class DataGrid _
    Inherits Control
[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.

Constructors

  Name Description
Public method DataGrid Initializes a new instance of the DataGrid class.

Top

Properties

  Name Description
Public property ActualHeight Gets the rendered height of a FrameworkElement. (Inherited from FrameworkElement.)
Public property ActualWidth Gets the rendered width of a FrameworkElement. (Inherited from FrameworkElement.)
Public property AllowDrop Gets 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 property AlternatingRowBackground Gets or sets the Brush that is used to paint the background of odd-numbered rows.
Public property AreRowDetailsFrozen Gets 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 property AreRowGroupHeadersFrozen Gets 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 property AutoGenerateColumns Gets or sets a value that indicates whether columns are created automatically when the ItemsSource property is set.
Public property Background Gets or sets a brush that provides the background of the control. (Inherited from Control.)
Public property BorderBrush Gets or sets a brush that describes the border background of a control. (Inherited from Control.)
Public property BorderThickness Gets or sets the border thickness of a control. (Inherited from Control.)
Public property CacheMode Gets or sets a value that indicates that rendered content should be cached when possible. (Inherited from UIElement.)
Public property CanUserReorderColumns Gets or sets a value that indicates whether the user can change the column display order by dragging column headers with the mouse.
Public property CanUserResizeColumns Gets or sets a value that indicates whether the user can adjust column widths using the mouse.
Public property CanUserSortColumns Gets or sets a value that indicates whether the user can sort columns by clicking the column header.
Public property CellStyle Gets or sets the style that is used when rendering the data grid cells.
Public property CharacterSpacing Gets or sets the distance between characters of text in the control measured in 1000ths of the font size. (Inherited from Control.)
Public property Clip Gets or sets the Geometry used to define the outline of the contents of a UIElement. (Inherited from UIElement.)
Public property ClipboardCopyMode Gets or sets a value that indicates how data is copied to the clipboard.
Public property ColumnHeaderHeight Gets or sets the height of the column headers row.
Public property ColumnHeaderStyle Gets or sets the style that is used when rendering the column headers.
Public property Columns Gets a collection that contains all the columns in the control.
Public property ColumnWidth Gets or sets the standard width or automatic sizing mode of columns in the control.
Public property CurrentColumn Gets or sets the column that contains the current cell.
Protected property CurrentItem Gets the data item bound to the row that contains the current cell.
Public property Cursor Gets or sets the cursor image that displays while the mouse pointer is over a FrameworkElement. (Inherited from FrameworkElement.)
Public property DataContext Gets or sets the data context for a FrameworkElement when it participates in data binding. (Inherited from FrameworkElement.)
Protected property DefaultStyleKey Gets or sets the key that references the default style for the control. (Inherited from Control.)
Public property DesiredSize Gets the size that this UIElement computed during the measure pass of the layout process. (Inherited from UIElement.)
Public property Dispatcher Gets the Dispatcher this object is associated with. (Inherited from DependencyObject.)
Public property DragIndicatorStyle Gets or sets the style that is used when rendering the drag indicator that is displayed while dragging column headers.
Public property DropLocationIndicatorStyle Gets or sets the style that is used when rendering the column headers.
Public property Effect Gets or sets the pixel shader effect to use for rendering this UIElement. (Inherited from UIElement.)
Public property FlowDirection Gets or sets the direction that text and other user interface elements flow within any parent element that controls their layout. (Inherited from FrameworkElement.)
Public property FontFamily Gets or sets the font used to display text in the control. (Inherited from Control.)
Public property FontSize Gets or sets the size of the text in this control. (Inherited from Control.)
Public property FontStretch Gets or sets the degree to which a font is condensed or expanded on the screen. (Inherited from Control.)
Public property FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control.)
Public property FontWeight Gets or sets the thickness of the specified font. (Inherited from Control.)
Public property Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control.)
Public property FrozenColumnCount Gets or sets the number of columns that the user cannot scroll horizontally.
Public property GridLinesVisibility Gets or sets a value that indicates which grid lines separating inner cells are shown.
Public property HeadersVisibility Gets or sets a value that indicates the visibility of row and column headers.
Public property Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement.)
Public property HorizontalAlignment Gets 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 property HorizontalContentAlignment Gets or sets the horizontal alignment of the control's content. (Inherited from Control.)
Public property HorizontalGridLinesBrush Gets or sets the Brush that is used to paint grid lines separating rows.
Public property HorizontalScrollBarVisibility Gets or sets a value that indicates how the horizontal scroll bar is displayed.
Public property IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control.)
Public property IsHitTestVisible Gets or sets whether the contained area of this UIElement can return true values for hit testing. (Inherited from UIElement.)
Public property IsReadOnly Gets or sets a value that indicates whether the user can edit the values in the control.
Public property IsTabStop Gets or sets a value that indicates whether a control is included in tab navigation. (Inherited from Control.)
Public property IsValid Gets a value that indicates whether data in the grid is valid.
Public property ItemsSource Gets or sets a collection that is used to generate the content of the control.
Public property Language Gets or sets localization/globalization language information that applies to a FrameworkElement. (Inherited from FrameworkElement.)
Public property Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement.)
Public property MaxColumnWidth Gets or sets the maximum width of columns in the DataGrid.
Public property MaxHeight Gets or sets the maximum height constraint of a FrameworkElement. (Inherited from FrameworkElement.)
Public property MaxWidth Gets or sets the maximum width constraint of a FrameworkElement. (Inherited from FrameworkElement.)
Public property MinColumnWidth Gets or sets the minimum width of columns in the DataGrid.
Public property MinHeight Gets or sets the minimum height constraint of a FrameworkElement. (Inherited from FrameworkElement.)
Public property MinWidth Gets or sets the minimum width constraint of a FrameworkElement. (Inherited from FrameworkElement.)
Public property Name Gets 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 property Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement.)
Public property OpacityMask Gets or sets the brush used to alter the opacity of regions of this object. (Inherited from UIElement.)
Public property Padding Gets or sets the padding inside a control. (Inherited from Control.)
Public property Parent Gets the parent object of this FrameworkElement in the object tree. (Inherited from FrameworkElement.)
Public property Projection Gets or sets the perspective projection (3-D effect) to apply when rendering this UIElement. (Inherited from UIElement.)
Public property RenderSize Gets the final render size of a UIElement. (Inherited from UIElement.)
Public property RenderTransform Gets or sets transform information that affects the rendering position of a UIElement. (Inherited from UIElement.)
Public property RenderTransformOrigin Gets or sets the origin point of any possible render transform declared by RenderTransform, relative to the bounds of the UIElement. (Inherited from UIElement.)
Public property Resources Gets 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 property RowBackground Gets or sets the Brush that is used to paint row backgrounds.
Public property RowDetailsTemplate Gets or sets the template that is used to display the content of the details section of rows.
Public property RowDetailsVisibilityMode Gets or sets a value that indicates when the details sections of rows are displayed.
Public property RowGroupHeaderStyles Gets the style that is used when rendering the row group header.
Public property RowHeaderStyle Gets or sets the style that is used when rendering the row headers.
Public property RowHeaderWidth Gets or sets the width of the row header column.
Public property RowHeight Gets or sets the standard height of rows in the control.
Public property RowStyle Gets or sets the style that is used when rendering the rows.
Public property SelectedIndex Gets or sets the index of the current selection.
Public property SelectedItem Gets or sets the data item corresponding to the selected row.
Public property SelectedItems Gets a list that contains the data items corresponding to the selected rows.
Public property SelectionMode Gets or sets the selection behavior of the data grid.
Public property Style Gets or sets an instance Style that is applied for this object during rendering. (Inherited from FrameworkElement.)
Public property TabIndex Gets 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 property TabNavigation Gets or sets a value that modifies how tabbing and TabIndex work for this control. (Inherited from Control.)
Public property Tag Gets or sets an arbitrary object value that can be used to store custom information about this object. (Inherited from FrameworkElement.)
Public property Template Gets or sets a control template. (Inherited from Control.)
Public property Triggers Gets the collection of triggers for animations that are defined for a FrameworkElement. (Inherited from FrameworkElement.)
Public property UseLayoutRounding Gets 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 property VerticalAlignment Gets 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 property VerticalContentAlignment Gets or sets the vertical alignment of the control's content. (Inherited from Control.)
Public property VerticalGridLinesBrush Gets or sets the Brush that is used to paint grid lines separating columns.
Public property VerticalScrollBarVisibility Gets or sets a value that indicates how the vertical scroll bar is displayed.
Public property Visibility Gets 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 property Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement.)

Top

Methods

  Name Description
Public method AddHandler Adds 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 method ApplyTemplate Loads the relevant control template so that its parts can be referenced. (Inherited from Control.)
Public method Arrange Positions 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 method ArrangeOverride Arranges the content of the DataGrid. (Overrides FrameworkElement.ArrangeOverride(Size).)
Public method BeginEdit() 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 method BeginEdit(RoutedEventArgs) Causes the data grid to enter editing mode for the current cell and current row in the specified keyboard and mouse state.
Public method CancelEdit() Causes the data grid to cancel the current edit, restore the original value, and exit editing mode.
Public method CancelEdit(DataGridEditingUnit) Causes the data grid to cancel the current edit, restore the original value, and exit editing mode.
Public method CaptureMouse Sets mouse capture to a UIElement. (Inherited from UIElement.)
Public method CheckAccess Determines whether the calling thread has access to this object. (Inherited from DependencyObject.)
Public method ClearValue Clears the local value of a dependency property. (Inherited from DependencyObject.)
Public method CollapseRowGroup Collapses data grid row groups.
Public method CommitEdit() Causes the data grid to commit the current edit to the data source and exit editing mode.
Public method CommitEdit(DataGridEditingUnit, Boolean) Causes the data grid to commit the current edit to the data source, and optionally exit editing mode.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Public method ExpandRowGroup Expands data grid row groups.
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public method FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement.)
Public method Focus Attempts to set the focus on the control. (Inherited from Control.)
Public method GetAnimationBaseValue Returns any base value established for a Silverlight dependency property, which would apply in cases where an animation is not active. (Inherited from DependencyObject.)
Public method GetBindingExpression Retrieves the BindingExpression for a dependency property where a binding is established. (Inherited from FrameworkElement.)
Public method GetGroupFromItem Gets the row group that the specified item belongs to.
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Protected method GetTemplateChild Retrieves the named element in the instantiated ControlTemplate visual tree. (Inherited from Control.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject.)
Public method InvalidateArrange Invalidates 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 method InvalidateMeasure Invalidates the measurement state (layout) for a UIElement. (Inherited from UIElement.)
Public method Measure Updates 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 method MeasureOverride Measures the children of a DataGrid in preparation of arranging them during the ArrangeOverride pass. (Overrides FrameworkElement.MeasureOverride(Size).)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method OnApplyTemplate Builds the visual tree for the DataGrid control when a new template is applied. (Overrides FrameworkElement.OnApplyTemplate().)
Protected method OnAutoGeneratingColumn Raises the AutoGeneratingColumn event.
Protected method OnBeginningEdit Raises the BeginningEdit event.
Protected method OnCellEditEnded Raises the CellEditEnded event.
Protected method OnCellEditEnding Raises the CellEditEnding event.
Protected method OnColumnDisplayIndexChanged Raises the ColumnDisplayIndexChanged event.
Protected method OnColumnReordered Raises the ColumnReordered event.
Protected method OnColumnReordering Raises the ColumnReordering event.
Protected method OnCopyingRowClipboardContent Raises the CopyingRowClipboardContent event.
Protected method OnCreateAutomationPeer Returns a DataGridAutomationPeer for use by the Silverlight automation infrastructure. (Overrides UIElement.OnCreateAutomationPeer().)
Protected method OnCurrentCellChanged Raises the CurrentCellChanged event.
Protected method OnDragEnter Called before the DragEnter event occurs. (Inherited from Control.)
Protected method OnDragLeave Called before the DragLeave event occurs. (Inherited from Control.)
Protected method OnDragOver Called before the DragOver event occurs. (Inherited from Control.)
Protected method OnDrop Called before the Drop event occurs. (Inherited from Control.)
Protected method OnGotFocus Called before the GotFocus event occurs. (Inherited from Control.)
Protected method OnKeyDown Called before the KeyDown event occurs. (Inherited from Control.)
Protected method OnKeyUp Called before the KeyUp event occurs. (Inherited from Control.)
Protected method OnLoadingRow Raises the LoadingRow event.
Protected method OnLoadingRowDetails Raises the LoadingRowDetails event.
Protected method OnLoadingRowGroup Raises the LoadingRowGroup event.
Protected method OnLostFocus Called before the LostFocus event occurs. (Inherited from Control.)
Protected method OnLostMouseCapture Called before the LostMouseCapture event occurs to provide handling for the event in a derived class without attaching a delegate. (Inherited from Control.)
Protected method OnMouseEnter Called before the MouseEnter event occurs. (Inherited from Control.)
Protected method OnMouseLeave Called before the MouseLeave event occurs. (Inherited from Control.)
Protected method OnMouseLeftButtonDown Called before the MouseLeftButtonDown event occurs. (Inherited from Control.)
Protected method OnMouseLeftButtonUp Called before the MouseLeftButtonUp event occurs. (Inherited from Control.)
Protected method OnMouseMove Called before the MouseMove event occurs. (Inherited from Control.)
Protected method OnMouseRightButtonDown Called before the MouseRightButtonDown event occurs. (Inherited from Control.)
Protected method OnMouseRightButtonUp Called before the MouseRightButtonUp event occurs. (Inherited from Control.)
Protected method OnMouseWheel Provides handling for the MouseWheel event. (Overrides Control.OnMouseWheel(MouseWheelEventArgs).)
Protected method OnPreparingCellForEdit Raises the PreparingCellForEdit event.
Protected method OnRowDetailsVisibilityChanged Raises the RowDetailsVisibilityChanged event.
Protected method OnRowEditEnded Raises the RowEditEnded event.
Protected method OnRowEditEnding Raises the RowEditEnding event.
Protected method OnSelectionChanged Raises the SelectionChanged event.
Protected method OnTextInput Called before the TextInput event occurs. (Inherited from Control.)
Protected method OnTextInputStart Called before the TextInputStart event occurs. (Inherited from Control.)
Protected method OnTextInputUpdate Called before the TextInputUpdate event occurs. (Inherited from Control.)
Protected method OnUnloadingRow Raises the UnloadingRow event.
Protected method OnUnloadingRowDetails Raises the UnloadingRowDetails event.
Protected method OnUnloadingRowGroup Raises the UnloadingRowGroup event.
Public method ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject.)
Public method ReleaseMouseCapture Removes mouse capture from a UIElement. After this call, typically no object holds mouse capture. (Inherited from UIElement.)
Public method RemoveHandler Removes the specified routed event handler from this UIElement. (Inherited from UIElement.)
Public method ScrollIntoView Scrolls the DataGrid vertically to display the row for the specified data item and scrolls the DataGrid horizontally to display the specified column.
Public method SetBinding Attaches a binding to a FrameworkElement, using the provided binding object, and returns a BindingExpressionBase for possible later use. (Inherited from FrameworkElement.)
Public method SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject.)
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Public method TransformToVisual Returns a transform object that can be used to transform coordinates from the UIElement to the specified object. (Inherited from UIElement.)
Public method UpdateLayout Ensures that all positions of child objects of a UIElement are properly updated for layout. (Inherited from UIElement.)

Top

Events

  Name Description
Public event AutoGeneratingColumn Occurs 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 event BeginningEdit Occurs before a cell or row enters editing mode.
Public event BindingValidationError Occurs when a data validation error is reported by a binding source. (Inherited from FrameworkElement.)
Public event CellEditEnded Occurs when a cell edit has been committed or canceled.
Public event CellEditEnding Occurs when a cell edit is ending.
Public event ColumnDisplayIndexChanged Occurs when the DisplayIndex property of a column changes.
Public event ColumnHeaderDragCompleted Occurs when the user drops a column header that was being dragged using the mouse.
Public event ColumnHeaderDragDelta Occurs one or more times while the user drags a column header using the mouse.
Public event ColumnHeaderDragStarted Occurs when the user begins dragging a column header using the mouse.
Public event ColumnReordered Occurs when a DataGrid column has moved to a new position in the display order.
Public event ColumnReordering Occurs before a DataGrid column moves to a new position in the display order.
Public event CopyingRowClipboardContent Occurs when the row is prepared for a clipboard copy operation.
Public event CurrentCellChanged Occurs when a different cell becomes the current cell.
Public event DataContextChanged Occurs when the data context for this element changes. (Inherited from FrameworkElement.)
Public event DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement.)
Public event DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement.)
Public event DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement.)
Public event Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement.)
Public event GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement.)
Public event IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control.)
Public event KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement.)
Public event KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement.)
Public event LayoutUpdated Occurs when the layout of the Silverlight visual tree changes. (Inherited from FrameworkElement.)
Public event Loaded Occurs when a FrameworkElement has been constructed and added to the object tree. (Inherited from FrameworkElement.)
Public event LoadingRow Occurs after a DataGridRow is instantiated, so that you can customize it before it is used.
Public event LoadingRowDetails Occurs when a new row details template is applied to a row, so that you can customize the details section before it is used.
Public event LoadingRowGroup Occurs when a row group header is loading, so that you can customize the header before it is used.
Public event LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement.)
Public event LostMouseCapture Occurs when the UIElement loses mouse capture. (Inherited from UIElement.)
Public event MediaCommand Occurs when a button is pressed on a remote control. (Inherited from UIElement.)
Public event MouseEnter Occurs when the mouse (or a stylus) enters the bounding area of a UIElement. (Inherited from UIElement.)
Public event MouseLeave Occurs when the mouse (or the stylus) leaves the bounding area of a UIElement. (Inherited from UIElement.)
Public event MouseLeftButtonDown Occurs 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 event MouseLeftButtonUp Occurs 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 event MouseMove Occurs 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 event MouseRightButtonDown Occurs when the right mouse button is pressed while the mouse pointer is over a UIElement. (Inherited from UIElement.)
Public event MouseRightButtonUp Occurs 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 event MouseWheel Occurs when the user rotates the mouse wheel while the mouse pointer is over a UIElement, or the UIElement has focus. (Inherited from UIElement.)
Public event PreparingCellForEdit Occurs when a cell in a DataGridTemplateColumn enters editing mode.
Public event RowDetailsVisibilityChanged Occurs when the RowDetailsVisibilityMode property value changes.
Public event RowEditEnded Occurs when a row edit has been committed or canceled.
Public event RowEditEnding Occurs when a row edit is ending.
Public event SelectionChanged Occurs when the SelectedItem or SelectedItems property value changes.
Public event SizeChanged Occurs when either the ActualHeight or the ActualWidth properties change value on a FrameworkElement. (Inherited from FrameworkElement.)
Public event TextInput Occurs when a UI element gets text in a device-independent manner. (Inherited from UIElement.)
Public event TextInputStart Occurs when a UI element initially gets text in a device-independent manner. (Inherited from UIElement.)
Public event TextInputUpdate Occurs when text continues to be composed via an input method editor (IME). (Inherited from UIElement.)
Public event Unloaded Occurs when this object is no longer connected to the main object tree. (Inherited from FrameworkElement.)
Public event UnloadingRow Occurs when a DataGridRow object becomes available for reuse.
Public event UnloadingRowDetails Occurs when a row details element becomes available for reuse.
Public event UnloadingRowGroup Occurs when a row group is unloading.

Top

Fields

  Name Description
Public fieldStatic member AlternatingRowBackgroundProperty Identifies the AlternatingRowBackground dependency property.
Public fieldStatic member AreRowDetailsFrozenProperty Identifies the AreRowDetailsFrozen dependency property.
Public fieldStatic member AreRowGroupHeadersFrozenProperty Identifies the AreRowGroupHeadersFrozen dependency property.
Public fieldStatic member AutoGenerateColumnsProperty Identifies the AutoGenerateColumns dependency property.
Public fieldStatic member CanUserReorderColumnsProperty Identifies the CanUserReorderColumns dependency property.
Public fieldStatic member CanUserResizeColumnsProperty Identifies the CanUserResizeColumns dependency property.
Public fieldStatic member CanUserSortColumnsProperty Identifies the CanUserSortColumns dependency property.
Public fieldStatic member CellStyleProperty Identifies the CellStyle dependency property.
Public fieldStatic member ClipboardCopyModeProperty Identifies the ClipboardCopyMode dependency property.
Public fieldStatic member ColumnHeaderHeightProperty Identifies the ColumnHeaderHeight dependency property.
Public fieldStatic member ColumnHeaderStyleProperty Identifies the ColumnHeaderStyle dependency property.
Public fieldStatic member ColumnWidthProperty Identifies the ColumnWidth dependency property.
Public fieldStatic member DragIndicatorStyleProperty Identifies the DragIndicatorStyle dependency property.
Public fieldStatic member DropLocationIndicatorStyleProperty Identifies the DropLocationIndicatorStyle dependency property.
Public fieldStatic member FrozenColumnCountProperty Identifies the FrozenColumnCount dependency property.
Public fieldStatic member GridLinesVisibilityProperty Identifies the GridLinesVisibility dependency property.
Public fieldStatic member HeadersVisibilityProperty Identifies the HeadersVisibility dependency property.
Public fieldStatic member HorizontalGridLinesBrushProperty Identifies the HorizontalGridLinesBrush dependency property.
Public fieldStatic member HorizontalScrollBarVisibilityProperty Identifies the HorizontalScrollBarVisibility dependency property.
Public fieldStatic member IsReadOnlyProperty Identifies the IsReadOnly dependency property.
Public fieldStatic member IsValidProperty Identifies the IsValid dependency property.
Public fieldStatic member ItemsSourceProperty Identifies the ItemsSource dependency property.
Public fieldStatic member MaxColumnWidthProperty Identifies the MaxColumnWidth dependency property.
Public fieldStatic member MinColumnWidthProperty Identifies the MinColumnWidth dependency property.
Public fieldStatic member RowBackgroundProperty Identifies the RowBackground dependency property.
Public fieldStatic member RowDetailsTemplateProperty Identifies the RowDetailsTemplate dependency property.
Public fieldStatic member RowDetailsVisibilityModeProperty Identifies the RowDetailsVisibilityMode dependency property.
Public fieldStatic member RowHeaderStyleProperty Identifies the RowHeaderStyle dependency property.
Public fieldStatic member RowHeaderWidthProperty Identifies the RowHeaderWidth dependency property.
Public fieldStatic member RowHeightProperty Identifies the RowHeight dependency property.
Public fieldStatic member RowStyleProperty Identifies the RowStyle dependency property.
Public fieldStatic member SelectedIndexProperty Identifies the SelectedIndex dependency property.
Public fieldStatic member SelectedItemProperty Identifies the SelectedItem dependency property.
Public fieldStatic member SelectionModeProperty Identifies the SelectionMode dependency property.
Public fieldStatic member VerticalGridLinesBrushProperty Identifies the VerticalGridLinesBrush dependency property.
Public fieldStatic member VerticalScrollBarVisibilityProperty Identifies the VerticalScrollBarVisibility dependency property.

Top

Remarks

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.

Examples

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="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"     
    xmlns:sdk="https://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>
Partial Public Class Page
    Inherits UserControl

    Public Sub New()
        InitializeComponent()

        dataGrid1.ItemsSource = Customer.GetSampleCustomerList()
        dataGrid3.ItemsSource = Customer.GetSampleCustomerList()
        dataGrid4.ItemsSource = Customer.GetSampleCustomerList()
        dataGrid5.ItemsSource = Customer.GetSampleCustomerList()
    End Sub

End Class

Public Class Customer
    Dim m_FirstName As String
    Dim m_LastName As String
    Dim m_Address As String
    Dim m_IsNew As Boolean
    Dim m_IsSubscribed As Boolean?

    Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal address As String, ByVal isNew As Boolean, ByVal isSubscribed As Boolean?)
        Me.FirstName = firstName
        Me.LastName = lastName
        Me.Address = address
        Me.IsNew = isNew
        Me.IsSubscribed = isSubscribed
    End Sub

    Property FirstName() As String
        Get
            Return m_FirstName
        End Get
        Set(ByVal value As String)
            m_FirstName = value
        End Set
    End Property

    Property LastName() As String
        Get
            Return m_LastName
        End Get
        Set(ByVal value As String)
            m_LastName = value
        End Set
    End Property

    Property Address() As String
        Get
            Return m_Address
        End Get
        Set(ByVal value As String)
            m_Address = value
        End Set
    End Property

    Property IsNew() As Boolean
        Get
            Return m_IsNew
        End Get
        Set(ByVal value As Boolean)
            m_IsNew = value
        End Set
    End Property

    Property IsSubscribed() As Boolean?
        Get
            Return m_IsSubscribed
        End Get
        Set(ByVal value As Boolean?)
            m_IsSubscribed = value
        End Set
    End Property

    Public Shared Function GetSampleCustomerList() As List(Of Customer)
        Return New List(Of Customer)(New Customer() _
               {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, Nothing), _
                New Customer("D.", "Three", "78 South Ninth Street, Apartment 10", True, True)})
    End Function
End Class
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)
            });
        }
    }
}

Version Information

Silverlight

Supported in: 5, 4, 3

Platforms

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

Thread Safety

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