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.
Properties
Name | Description | |
---|---|---|
ActualHeight | Gets the rendered height of a FrameworkElement. (Inherited from FrameworkElement.) | |
ActualWidth | Gets the rendered width of a FrameworkElement. (Inherited from FrameworkElement.) | |
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.) | |
AlternatingRowBackground | Gets or sets the Brush that is used to paint the background of odd-numbered rows. | |
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. | |
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. | |
AutoGenerateColumns | Gets or sets a value that indicates whether columns are created automatically when the ItemsSource property is set. | |
Background | Gets or sets a brush that provides the background of the control. (Inherited from Control.) | |
BorderBrush | Gets or sets a brush that describes the border background of a control. (Inherited from Control.) | |
BorderThickness | Gets or sets the border thickness of a control. (Inherited from Control.) | |
CacheMode | Gets or sets a value that indicates that rendered content should be cached when possible. (Inherited from UIElement.) | |
CanUserReorderColumns | Gets or sets a value that indicates whether the user can change the column display order by dragging column headers with the mouse. | |
CanUserResizeColumns | Gets or sets a value that indicates whether the user can adjust column widths using the mouse. | |
CanUserSortColumns | Gets or sets a value that indicates whether the user can sort columns by clicking the column header. | |
CellStyle | Gets or sets the style that is used when rendering the data grid cells. | |
CharacterSpacing | Gets or sets the distance between characters of text in the control measured in 1000ths of the font size. (Inherited from Control.) | |
Clip | Gets or sets the Geometry used to define the outline of the contents of a UIElement. (Inherited from UIElement.) | |
ClipboardCopyMode | Gets or sets a value that indicates how data is copied to the clipboard. | |
ColumnHeaderHeight | Gets or sets the height of the column headers row. | |
ColumnHeaderStyle | Gets or sets the style that is used when rendering the column headers. | |
Columns | Gets a collection that contains all the columns in the control. | |
ColumnWidth | Gets or sets the standard width or automatic sizing mode of columns in the control. | |
CurrentColumn | Gets or sets the column that contains the current cell. | |
CurrentItem | Gets the data item bound to the row that contains the current cell. | |
Cursor | Gets or sets the cursor image that displays while the mouse pointer is over a FrameworkElement. (Inherited from FrameworkElement.) | |
DataContext | Gets or sets the data context for a FrameworkElement when it participates in data binding. (Inherited from FrameworkElement.) | |
DefaultStyleKey | Gets or sets the key that references the default style for the control. (Inherited from Control.) | |
DesiredSize | Gets the size that this UIElement computed during the measure pass of the layout process. (Inherited from UIElement.) | |
Dispatcher | Gets the Dispatcher this object is associated with. (Inherited from DependencyObject.) | |
DragIndicatorStyle | Gets or sets the style that is used when rendering the drag indicator that is displayed while dragging column headers. | |
DropLocationIndicatorStyle | Gets or sets the style that is used when rendering the column headers. | |
Effect | Gets or sets the pixel shader effect to use for rendering this UIElement. (Inherited from UIElement.) | |
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.) | |
FontFamily | Gets or sets the font used to display text in the control. (Inherited from Control.) | |
FontSize | Gets or sets the size of the text in this control. (Inherited from Control.) | |
FontStretch | Gets or sets the degree to which a font is condensed or expanded on the screen. (Inherited from Control.) | |
FontStyle | Gets or sets the style in which the text is rendered. (Inherited from Control.) | |
FontWeight | Gets or sets the thickness of the specified font. (Inherited from Control.) | |
Foreground | Gets or sets a brush that describes the foreground color. (Inherited from Control.) | |
FrozenColumnCount | Gets or sets the number of columns that the user cannot scroll horizontally. | |
GridLinesVisibility | Gets or sets a value that indicates which grid lines separating inner cells are shown. | |
HeadersVisibility | Gets or sets a value that indicates the visibility of row and column headers. | |
Height | Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement.) | |
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.) | |
HorizontalContentAlignment | Gets or sets the horizontal alignment of the control's content. (Inherited from Control.) | |
HorizontalGridLinesBrush | Gets or sets the Brush that is used to paint grid lines separating rows. | |
HorizontalScrollBarVisibility | Gets or sets a value that indicates how the horizontal scroll bar is displayed. | |
IsEnabled | Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control.) | |
IsHitTestVisible | Gets or sets whether the contained area of this UIElement can return true values for hit testing. (Inherited from UIElement.) | |
IsReadOnly | Gets or sets a value that indicates whether the user can edit the values in the control. | |
IsTabStop | Gets or sets a value that indicates whether a control is included in tab navigation. (Inherited from Control.) | |
IsValid | Gets a value that indicates whether data in the grid is valid. | |
ItemsSource | Gets or sets a collection that is used to generate the content of the control. | |
Language | Gets or sets localization/globalization language information that applies to a FrameworkElement. (Inherited from FrameworkElement.) | |
Margin | Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement.) | |
MaxColumnWidth | Gets or sets the maximum width of columns in the DataGrid. | |
MaxHeight | Gets or sets the maximum height constraint of a FrameworkElement. (Inherited from FrameworkElement.) | |
MaxWidth | Gets or sets the maximum width constraint of a FrameworkElement. (Inherited from FrameworkElement.) | |
MinColumnWidth | Gets or sets the minimum width of columns in the DataGrid. | |
MinHeight | Gets or sets the minimum height constraint of a FrameworkElement. (Inherited from FrameworkElement.) | |
MinWidth | Gets or sets the minimum width constraint of a FrameworkElement. (Inherited from FrameworkElement.) | |
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.) | |
Opacity | Gets or sets the degree of the object's opacity. (Inherited from UIElement.) | |
OpacityMask | Gets or sets the brush used to alter the opacity of regions of this object. (Inherited from UIElement.) | |
Padding | Gets or sets the padding inside a control. (Inherited from Control.) | |
Parent | Gets the parent object of this FrameworkElement in the object tree. (Inherited from FrameworkElement.) | |
Projection | Gets or sets the perspective projection (3-D effect) to apply when rendering this UIElement. (Inherited from UIElement.) | |
RenderSize | Gets the final render size of a UIElement. (Inherited from UIElement.) | |
RenderTransform | Gets or sets transform information that affects the rendering position of a UIElement. (Inherited from UIElement.) | |
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.) | |
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.) | |
RowBackground | Gets or sets the Brush that is used to paint row backgrounds. | |
RowDetailsTemplate | Gets or sets the template that is used to display the content of the details section of rows. | |
RowDetailsVisibilityMode | Gets or sets a value that indicates when the details sections of rows are displayed. | |
RowGroupHeaderStyles | Gets the style that is used when rendering the row group header. | |
RowHeaderStyle | Gets or sets the style that is used when rendering the row headers. | |
RowHeaderWidth | Gets or sets the width of the row header column. | |
RowHeight | Gets or sets the standard height of rows in the control. | |
RowStyle | Gets or sets the style that is used when rendering the rows. | |
SelectedIndex | Gets or sets the index of the current selection. | |
SelectedItem | Gets or sets the data item corresponding to the selected row. | |
SelectedItems | Gets a list that contains the data items corresponding to the selected rows. | |
SelectionMode | Gets or sets the selection behavior of the data grid. | |
Style | Gets or sets an instance Style that is applied for this object during rendering. (Inherited from FrameworkElement.) | |
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.) | |
TabNavigation | Gets or sets a value that modifies how tabbing and TabIndex work for this control. (Inherited from Control.) | |
Tag | Gets or sets an arbitrary object value that can be used to store custom information about this object. (Inherited from FrameworkElement.) | |
Template | Gets or sets a control template. (Inherited from Control.) | |
Triggers | Gets the collection of triggers for animations that are defined for a FrameworkElement. (Inherited from FrameworkElement.) | |
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.) | |
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.) | |
VerticalContentAlignment | Gets or sets the vertical alignment of the control's content. (Inherited from Control.) | |
VerticalGridLinesBrush | Gets or sets the Brush that is used to paint grid lines separating columns. | |
VerticalScrollBarVisibility | Gets or sets a value that indicates how the vertical scroll bar is displayed. | |
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.) | |
Width | Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement.) |
Top
Methods
Name | Description | |
---|---|---|
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.) | |
ApplyTemplate | Loads the relevant control template so that its parts can be referenced. (Inherited from Control.) | |
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.) | |
ArrangeOverride | Arranges the content of the DataGrid. (Overrides FrameworkElement.ArrangeOverride(Size).) | |
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. | |
BeginEdit(RoutedEventArgs) | Causes the data grid to enter editing mode for the current cell and current row in the specified keyboard and mouse state. | |
CancelEdit() | Causes the data grid to cancel the current edit, restore the original value, and exit editing mode. | |
CancelEdit(DataGridEditingUnit) | Causes the data grid to cancel the current edit, restore the original value, and exit editing mode. | |
CaptureMouse | Sets mouse capture to a UIElement. (Inherited from UIElement.) | |
CheckAccess | Determines whether the calling thread has access to this object. (Inherited from DependencyObject.) | |
ClearValue | Clears the local value of a dependency property. (Inherited from DependencyObject.) | |
CollapseRowGroup | Collapses data grid row groups. | |
CommitEdit() | Causes the data grid to commit the current edit to the data source and exit editing mode. | |
CommitEdit(DataGridEditingUnit, Boolean) | Causes the data grid to commit the current edit to the data source, and optionally exit editing mode. | |
Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | |
ExpandRowGroup | Expands data grid row groups. | |
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.) | |
FindName | Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement.) | |
Focus | Attempts to set the focus on the control. (Inherited from Control.) | |
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.) | |
GetBindingExpression | Retrieves the BindingExpression for a dependency property where a binding is established. (Inherited from FrameworkElement.) | |
GetGroupFromItem | Gets the row group that the specified item belongs to. | |
GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | |
GetTemplateChild | Retrieves the named element in the instantiated ControlTemplate visual tree. (Inherited from Control.) | |
GetType | Gets the Type of the current instance. (Inherited from Object.) | |
GetValue | Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject.) | |
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.) | |
InvalidateMeasure | Invalidates the measurement state (layout) for a UIElement. (Inherited from UIElement.) | |
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.) | |
MeasureOverride | Measures the children of a DataGrid in preparation of arranging them during the ArrangeOverride pass. (Overrides FrameworkElement.MeasureOverride(Size).) | |
MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | |
OnApplyTemplate | Builds the visual tree for the DataGrid control when a new template is applied. (Overrides FrameworkElement.OnApplyTemplate().) | |
OnAutoGeneratingColumn | Raises the AutoGeneratingColumn event. | |
OnBeginningEdit | Raises the BeginningEdit event. | |
OnCellEditEnded | Raises the CellEditEnded event. | |
OnCellEditEnding | Raises the CellEditEnding event. | |
OnColumnDisplayIndexChanged | Raises the ColumnDisplayIndexChanged event. | |
OnColumnReordered | Raises the ColumnReordered event. | |
OnColumnReordering | Raises the ColumnReordering event. | |
OnCopyingRowClipboardContent | Raises the CopyingRowClipboardContent event. | |
OnCreateAutomationPeer | Returns a DataGridAutomationPeer for use by the Silverlight automation infrastructure. (Overrides UIElement.OnCreateAutomationPeer().) | |
OnCurrentCellChanged | Raises the CurrentCellChanged event. | |
OnDragEnter | Called before the DragEnter event occurs. (Inherited from Control.) | |
OnDragLeave | Called before the DragLeave event occurs. (Inherited from Control.) | |
OnDragOver | Called before the DragOver event occurs. (Inherited from Control.) | |
OnDrop | Called before the Drop event occurs. (Inherited from Control.) | |
OnGotFocus | Called before the GotFocus event occurs. (Inherited from Control.) | |
OnKeyDown | Called before the KeyDown event occurs. (Inherited from Control.) | |
OnKeyUp | Called before the KeyUp event occurs. (Inherited from Control.) | |
OnLoadingRow | Raises the LoadingRow event. | |
OnLoadingRowDetails | Raises the LoadingRowDetails event. | |
OnLoadingRowGroup | Raises the LoadingRowGroup event. | |
OnLostFocus | Called before the LostFocus event occurs. (Inherited from Control.) | |
OnLostMouseCapture | Called before the LostMouseCapture event occurs to provide handling for the event in a derived class without attaching a delegate. (Inherited from Control.) | |
OnMouseEnter | Called before the MouseEnter event occurs. (Inherited from Control.) | |
OnMouseLeave | Called before the MouseLeave event occurs. (Inherited from Control.) | |
OnMouseLeftButtonDown | Called before the MouseLeftButtonDown event occurs. (Inherited from Control.) | |
OnMouseLeftButtonUp | Called before the MouseLeftButtonUp event occurs. (Inherited from Control.) | |
OnMouseMove | Called before the MouseMove event occurs. (Inherited from Control.) | |
OnMouseRightButtonDown | Called before the MouseRightButtonDown event occurs. (Inherited from Control.) | |
OnMouseRightButtonUp | Called before the MouseRightButtonUp event occurs. (Inherited from Control.) | |
OnMouseWheel | Provides handling for the MouseWheel event. (Overrides Control.OnMouseWheel(MouseWheelEventArgs).) | |
OnPreparingCellForEdit | Raises the PreparingCellForEdit event. | |
OnRowDetailsVisibilityChanged | Raises the RowDetailsVisibilityChanged event. | |
OnRowEditEnded | Raises the RowEditEnded event. | |
OnRowEditEnding | Raises the RowEditEnding event. | |
OnSelectionChanged | Raises the SelectionChanged event. | |
OnTextInput | Called before the TextInput event occurs. (Inherited from Control.) | |
OnTextInputStart | Called before the TextInputStart event occurs. (Inherited from Control.) | |
OnTextInputUpdate | Called before the TextInputUpdate event occurs. (Inherited from Control.) | |
OnUnloadingRow | Raises the UnloadingRow event. | |
OnUnloadingRowDetails | Raises the UnloadingRowDetails event. | |
OnUnloadingRowGroup | Raises the UnloadingRowGroup event. | |
ReadLocalValue | Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject.) | |
ReleaseMouseCapture | Removes mouse capture from a UIElement. After this call, typically no object holds mouse capture. (Inherited from UIElement.) | |
RemoveHandler | Removes the specified routed event handler from this UIElement. (Inherited from UIElement.) | |
ScrollIntoView | Scrolls the DataGrid vertically to display the row for the specified data item and scrolls the DataGrid horizontally to display the specified column. | |
SetBinding | Attaches a binding to a FrameworkElement, using the provided binding object, and returns a BindingExpressionBase for possible later use. (Inherited from FrameworkElement.) | |
SetValue | Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject.) | |
ToString | Returns a string that represents the current object. (Inherited from Object.) | |
TransformToVisual | Returns a transform object that can be used to transform coordinates from the UIElement to the specified object. (Inherited from UIElement.) | |
UpdateLayout | Ensures that all positions of child objects of a UIElement are properly updated for layout. (Inherited from UIElement.) |
Top
Events
Name | Description | |
---|---|---|
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. | |
BeginningEdit | Occurs before a cell or row enters editing mode. | |
BindingValidationError | Occurs when a data validation error is reported by a binding source. (Inherited from FrameworkElement.) | |
CellEditEnded | Occurs when a cell edit has been committed or canceled. | |
CellEditEnding | Occurs when a cell edit is ending. | |
ColumnDisplayIndexChanged | Occurs when the DisplayIndex property of a column changes. | |
ColumnHeaderDragCompleted | Occurs when the user drops a column header that was being dragged using the mouse. | |
ColumnHeaderDragDelta | Occurs one or more times while the user drags a column header using the mouse. | |
ColumnHeaderDragStarted | Occurs when the user begins dragging a column header using the mouse. | |
ColumnReordered | Occurs when a DataGrid column has moved to a new position in the display order. | |
ColumnReordering | Occurs before a DataGrid column moves to a new position in the display order. | |
CopyingRowClipboardContent | Occurs when the row is prepared for a clipboard copy operation. | |
CurrentCellChanged | Occurs when a different cell becomes the current cell. | |
DataContextChanged | Occurs when the data context for this element changes. (Inherited from FrameworkElement.) | |
DragEnter | Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement.) | |
DragLeave | Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement.) | |
DragOver | Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement.) | |
Drop | Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement.) | |
GotFocus | Occurs when a UIElement receives focus. (Inherited from UIElement.) | |
IsEnabledChanged | Occurs when the IsEnabled property changes. (Inherited from Control.) | |
KeyDown | Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement.) | |
KeyUp | Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement.) | |
LayoutUpdated | Occurs when the layout of the Silverlight visual tree changes. (Inherited from FrameworkElement.) | |
Loaded | Occurs when a FrameworkElement has been constructed and added to the object tree. (Inherited from FrameworkElement.) | |
LoadingRow | Occurs after a DataGridRow is instantiated, so that you can customize it before it is used. | |
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. | |
LoadingRowGroup | Occurs when a row group header is loading, so that you can customize the header before it is used. | |
LostFocus | Occurs when a UIElement loses focus. (Inherited from UIElement.) | |
LostMouseCapture | Occurs when the UIElement loses mouse capture. (Inherited from UIElement.) | |
MediaCommand | Occurs when a button is pressed on a remote control. (Inherited from UIElement.) | |
MouseEnter | Occurs when the mouse (or a stylus) enters the bounding area of a UIElement. (Inherited from UIElement.) | |
MouseLeave | Occurs when the mouse (or the stylus) leaves the bounding area of a UIElement. (Inherited from UIElement.) | |
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.) | |
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.) | |
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.) | |
MouseRightButtonDown | Occurs when the right mouse button is pressed while the mouse pointer is over a UIElement. (Inherited from UIElement.) | |
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.) | |
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.) | |
PreparingCellForEdit | Occurs when a cell in a DataGridTemplateColumn enters editing mode. | |
RowDetailsVisibilityChanged | Occurs when the RowDetailsVisibilityMode property value changes. | |
RowEditEnded | Occurs when a row edit has been committed or canceled. | |
RowEditEnding | Occurs when a row edit is ending. | |
SelectionChanged | Occurs when the SelectedItem or SelectedItems property value changes. | |
SizeChanged | Occurs when either the ActualHeight or the ActualWidth properties change value on a FrameworkElement. (Inherited from FrameworkElement.) | |
TextInput | Occurs when a UI element gets text in a device-independent manner. (Inherited from UIElement.) | |
TextInputStart | Occurs when a UI element initially gets text in a device-independent manner. (Inherited from UIElement.) | |
TextInputUpdate | Occurs when text continues to be composed via an input method editor (IME). (Inherited from UIElement.) | |
Unloaded | Occurs when this object is no longer connected to the main object tree. (Inherited from FrameworkElement.) | |
UnloadingRow | Occurs when a DataGridRow object becomes available for reuse. | |
UnloadingRowDetails | Occurs when a row details element becomes available for reuse. | |
UnloadingRowGroup | Occurs when a row group is unloading. |
Top
Fields
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.
For information about adding and referencing a DataGrid control, see How to: Add a DataGrid Control to a Page.
Note: |
---|
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.
Note: |
---|
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.
<!-- 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.
See Also