XAML - DataGrid

A DataGrid represents a control that displays data in a customizable grid. It provides a flexible way to display a collection of data in rows and columns. The hierarchical inheritance of DataGrid class is as follows −
AlternatingRowBackground
Gets or sets the background brush for use on alternating rows.
AreRowDetailsFrozen
Gets or sets a value that indicates whether the row details can scroll horizontally.
AutoGenerateColumns
Gets or sets a value that indicates whether the columns are created automatically.
CanUserAddRows
Gets or sets a value that indicates whether the user can add new rows to the DataGrid.
CanUserDeleteRows
Gets or sets a value that indicates whether the user can delete rows from the DataGrid.
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 the width of columns by using the mouse.
CanUserResizeRows
Gets or sets a value that indicates whether the user can adjust the height of rows by using the mouse.
CanUserSortColumns
Gets or sets a value that indicates whether the user can sort columns by clicking the column header.
ColumnHeaderHeight
Gets or sets the height of the column headers row.
ColumnHeaderStyle
Gets or sets the style applied to all column headers in the DataGrid.
Columns
Gets a collection that contains all the columns in the DataGrid.
ColumnWidth
Gets or sets the standard width and sizing mode of columns and headers in the DataGrid.
CurrentCell
Gets or sets the cell that has focus.
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.
FrozenColumnCount
Gets or sets the number of non-scrolling columns.
HorizontalScrollBarVisibility
Gets or sets a value that indicates how horizontal scroll bars are displayed in the DataGrid.
IsReadOnly
Gets or sets a value that indicates whether the user can edit values in the DataGrid.
RowBackground
Gets or sets the default brush for the row background.
RowHeight
Gets or sets the suggested height for all rows.
SelectedCells
Gets the list of cells that are currently selected.
BeginEdit
Invokes the BeginEdit command, which will place the current cell or row into edit mode.
CancelEdit
Invokes the CancelEditCommand command for the cell or row currently in edit mode.
ClearDetailsVisibilityForItem
Clears the DetailsVisibility property for the DataGridRow that represents the specified data item.
ColumnFromDisplayIndex
Gets the DataGridColumn at the specified index.
CommitEdit
Invokes the CommitEditCommand command for the cell or row currently in edit mode.
GenerateColumns
Generates columns for the specified properties of an object.
GetDetailsVisibilityForItem
Gets the DetailsVisibility property for the DataGridRow that represents the specified data item.
OnApplyTemplate
When overridden in a derived class, is invoked whenever application code or internal processes call ApplyTemplate. (Overrides FrameworkElement.OnApplyTemplate())
ScrollIntoView
Scrolls the DataGrid vertically to display the row for the specified data item.
SelectAllCells
Selects all the cells in the DataGrid.
SetDetailsVisibilityForItem
Sets the value of the DetailsVisibility property for the DataGridRow that contains the specified object.
UnselectAllCells
Unselects all the cells in the DataGrid.
AddingNewItem
Occurs before a new item is added to the DataGrid.
AutoGeneratedColumns
Occurs when auto generation of all columns is completed.
AutoGeneratingColumn
Occurs when an individual column is auto-generated.
BeginningEdit
Occurs before a row or cell enters edit mode.
CellEditEnding
Occurs before a cell edit is committed or canceled.
ColumnDisplayIndexChanged
Occurs when the DisplayIndex property on one of the columns changes.
ColumnHeaderDragCompleted
Occurs when the user releases a column header after dragging it by using the mouse.
ColumnHeaderDragDelta
Occurs every time the mouse position changes while the user drags a column header.
ColumnHeaderDragStarted
Occurs when the user begins dragging a column header by using the mouse.
ColumnReordered
Occurs when a column moves to a new position in the display order.
ColumnReordering
Occurs before a column moves to a new position in the display order.
CopyingRowClipboardContent
Occurs after the default row content is prepared.
CurrentCellChanged
Occurs when the value of the CurrentCell property has changed.
InitializingNewItem
Occurs when a new item is created.
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.
PreparingCellForEdit
Occurs when a cell enters edit mode.
RowDetailsVisibilityChanged
Occurs when the visibility of a row details element changes.
RowEditEnding
Occurs before a row edit is committed or canceled.
SelectedCellsChanged
Occurs when the SelectedCells collection changes.
Sorting
Occurs when a column is being sorted.
UnloadingRow
Occurs when a DataGridRow object becomes available for reuse.
UnloadingRowDetails
Occurs when a row details element becomes available for reuse.
The following example shows how to display data in a DataGrid. Here is the XAML code to create two checkboxes with some properties and events.
<Window x:Class = "DataGrid.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:core = "clr-namespace:System;assembly = mscorlib" 
   xmlns:local = "clr-namespace:DataGrid" 
   Title = "MainWindow" Height = "350" Width = "525"> 
	
   <Window.Resources> 
      <ObjectDataProvider x:Key = "myEnum" MethodName = "GetValues" 
         ObjectType = "{x:Type core:Enum}"> 
			
         <ObjectDataProvider.MethodParameters> 
            <x:TypeExtension Type = "local:Party" /> 
         </ObjectDataProvider.MethodParameters> 
		</ObjectDataProvider> 
   </Window.Resources> 
	
   <Grid> 
      <DataGrid Name = "dataGrid" AlternatingRowBackground = "LightBlue" 
         AlternationCount = "2" AutoGenerateColumns = "False">
			
         <DataGrid.Columns> 
            <DataGridTextColumn Header = "Name" Binding = "{Binding Name}" />
            <DataGridTextColumn Header = "Title" Binding = "{Binding Title}" >
            <DataGridCheckBoxColumn Header = "ReElected?" Binding = "{Binding WasReElected}"/> 
				
            <DataGridComboBoxColumn Header = "Party"
               SelectedItemBinding = "{Binding Affiliation}" 
               ItemsSource = "{Binding Source = {StaticResource myEnum}}" /> 
         </DataGrid.Columns> 
      </DataGrid>
   </Grid> 
	
</Window>
Here is the implementation in C# for two different classes.
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks;
 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes;

namespace DataGrid { 
   /// <summary> 
      /// Interaction logic for MainWindow.xaml 
   /// </summary>
	
   public partial class MainWindow : Window { 
      public MainWindow() { 
         InitializeComponent(); dataGrid.ItemsSource = Employee.GetEmployees(); 
      }
   } 
	public enum Party { 
      Indepentent, Federalist, DemocratRepublican, 
   } 
}
Here is another Employee class implementation in C#.
public class Employee : INotifyPropertyChanged { 
   private string name; public string Name { 
      get { return name; } 
      set { 
         name = value; RaiseProperChanged(); 
      } 
   }
	private string title; public string Title { 
      get { return title; } 
		set { 
         title = value; 
         RaiseProperChanged();
      } 
   }
	private bool wasReElected;
	public bool WasReElected { 
      get { return wasReElected; } 
      set { 
         wasReElected = value; RaiseProperChanged(); 
      } 
   }
	private Party affiliation; public Party Affiliation {
      get { return affiliation; }
		set { 
         affiliation = value; RaiseProperChanged(); 
      } 
   }
	public static ObservableCollection<Employee> GetEmployees() {
      var employees = new ObservableCollection<Employee>(); 
      employees.Add(new Employee() {
         Name = "Ali", Title = "Minister", WasReElected = true, 
         Affiliation = Party.Indepentent }); 
			
      employees.Add(new Employee() { 
         Name = "Ahmed", Title = "CM", WasReElected = false, 
         Affiliation = Party.Federalist }); 
			
      employees.Add(new Employee() { 
         Name = "Amjad", Title = "PM", WasReElected = true, 
         Affiliation = Party.DemocratRepublican });
			
      employees.Add(new Employee() { 
         Name = "Waqas", Title = "Minister", WasReElected = false, 
         Affiliation = Party.Indepentent }); 
			
      employees.Add(new Employee() { 
         Name = "Bilal", Title = "Minister", WasReElected = true, 
         Affiliation = Party.Federalist });
			
      employees.Add(new Employee() { 
         Name = "Waqar", Title = "Minister", WasReElected = false,
         Affiliation = Party.DemocratRepublican }); 
			
      return employees; 
   }
   public event PropertyChangedEventHandler PropertyChanged;
	
   private void RaiseProperChanged( [CallerMemberName] string caller = "") { 
      if (PropertyChanged != null) { 
         PropertyChanged(this, new PropertyChangedEventArgs(caller)); 
      } 
   } 
}
When you compile and execute the above code, it will produce the following output −
We recommend you to execute the above example code and experiment with some other properties and events.