Walkthrough: Customizing the DataGrid Control Using Properties
Microsoft Silverlight will reach end of support after October 2021. Learn more.
The Silverlight DataGrid control supports common table formatting options, such as alternating row backgrounds and the ability to show or hide headers, gridlines, and scroll bars. These customizations can be made by setting DataGrid properties. Properties can be set in XAML at design time, or set in procedural code at run time.
This walkthrough illustrates the following tasks:
Creating a collection of data objects.
Creating the user interface to display the data.
Setting the data source for the list.
Creating the user interface for setting the DataGrid options.
Adding procedural code to modify DataGrid properties.
To view a running sample of the DataGrid control, click the following link.
Prerequisites
You need the following components to complete this walkthrough:
Silverlight 5.
Silverlight Tools for Visual Studio 2010.
Visual Studio 2010.
All of the Silverlight software is available from the Silverlight download site.
Creating a Silverlight Project
The first step is to create a Silverlight project.
To create a Silverlight project
- Create a new Silverlight Application project named DGBasicCustomization in Visual Basic or Visual C#. Leave the default selection Host the Silverlight application in a new Web site option checked. For more information, see How to: Create a New Silverlight Project.
Creating a Collection of Data to Display
Next, you create a collection of Task objects to be displayed in the DataGrid.
To create a collection of Task objects
Add a class named Task to the DGBasicCustomization project.
Add the following code to the Task class.
This code contains the Task class that represents the data objects to display in the DataGrid control.
Private m_Name As String Private m_DueDate As Date Private m_Complete As Boolean Private m_Notes As String Property Name() As String Get Return Me.m_Name End Get Set(ByVal value As String) Me.m_Name = value End Set End Property Property DueDate() As Date Get Return Me.m_DueDate End Get Set(ByVal value As Date) Me.m_DueDate = value End Set End Property Property Complete() As Boolean Get Return Me.m_Complete End Get Set(ByVal value As Boolean) Me.m_Complete = value End Set End Property Property Notes() As String Get Return Me.m_Notes End Get Set(ByVal value As String) Me.m_Notes = value End Set End Property
public string Name { get; set; } public DateTime DueDate { get; set; } public bool Complete { get; set; } public string Notes { get; set; }
Open MainPage.xaml.vb or MainPage.xaml.cs.
In the MainPage class constructor after the InitializeComponent method, add the following code.
This code creates a generic List<T> named taskList and uses a loop to populate the collection with Task objects. The taskList is then set as the ItemsSource of the DataGrid.
' Create a list to store task data. Dim taskList As List(Of Task) = New List(Of Task) Dim itemsCount As Integer = 10 ' Generate some task data and add it to the task list. For index = 1 To itemsCount taskList.Add(New Task() With _ {.Name = "Task " & index.ToString(), _ .DueDate = Date.Now.AddDays(index), _ .Complete = (index Mod 3 = 0), _ .Notes = "Task " & index.ToString() & " is due on " & Date.Now.AddDays(index) & ". Lorum ipsum..." _ }) Next Me.dataGrid1.ItemsSource = taskList
// Create a list to store task data. List<Task> taskList = new List<Task>(); int itemsCount = 10; // Generate some task data and add it to the task list. for (int i = 1; i <= itemsCount; i++) { taskList.Add(new Task() { Name = "Task " + i.ToString(), DueDate = DateTime.Now.AddDays(i), Complete = (i % 3 == 0), Notes = "Task " + i.ToString() + " is due on " + DateTime.Now.AddDays(i) + ". Lorum ipsum..." }); } this.dataGrid1.ItemsSource = taskList;
Creating the User Interface for the Task List
Next, you create the user interface for the task list by adding a DataGrid control to the page.
To create the user interface for the task list
In the DGBasicCustomization project, add a reference to the System.Windows.Controls.Data assembly. For more information, see How to: Add a DataGrid Control to a Page.
Open MainPage.xaml.
In the <UserControl> start tag, add the following XAML.
This XAML maps the sdk prefix to the Silverlight SDK namespace, as described in Prefixes and Mappings for Silverlight Libraries.
xmlns:sdk="https://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
In the <UserControl> start tag, change the value of the Width property to 600, and the value of the Height property to 700.
After the <UserControl> start tag, add the following XAML, replacing the existing <Grid> tags.
This XAML adds a StackPanel for layout purposes and a DataGrid named dataGrid1 to display the list of tasks.
<StackPanel x:Name="LayoutRoot" Background="White" Margin="5"> ... <sdk:DataGrid x:Name="dataGrid1" Height="350" Width="540" HorizontalAlignment="Left" > </sdk:DataGrid> </StackPanel>
Build and run the application.
When the application is running, you will see a DataGrid displaying the tasks in the taskList collection with its default appearance and behavior.
Creating the User Interface for the DataGrid Options
Next, you create the user interface for the DataGrid options.
To create the user interface for the DataGrid options
Open MainPage.xaml.
After the <StackPanel> start tag, add the following XAML.
This XAML adds selection controls that you will use to modify properties of the DataGrid at run time.
<StackPanel Margin="0,0,0,5"> <StackPanel Orientation="Horizontal"> <Border BorderBrush="Black" BorderThickness="1" Padding="3" Width="180"> <StackPanel> <TextBlock Text="DataGrid Options" FontSize="12" /> <CheckBox Content="Grid is read-only" Checked="cbReadOnly_Changed" Unchecked="cbReadOnly_Changed" /> <CheckBox Content="Freeze first column" Checked="cbFreezeColumn_Changed" Unchecked="cbFreezeColumn_Changed"/> <CheckBox Content="Hide first column" Checked="cbHideColumn_Changed" Unchecked="cbHideColumn_Changed"/> <CheckBox Content="Single Row Selection" Checked="cbSelectionMode_Changed" Unchecked="cbSelectionMode_Changed" /> <TextBlock Text="Column Options" FontSize="12" /> <CheckBox Content="Allow Column Reordering" IsChecked="true" Checked="cbColReorder_Changed" Unchecked="cbColReorder_Changed"/> <CheckBox Content="Allow Column Resizing" IsChecked="true" Checked="cbColResize_Changed" Unchecked="cbColResize_Changed"/> <CheckBox Content="Allow Column Sorting" IsChecked="true" Checked="cbColSort_Changed" Unchecked="cbColSort_Changed"/> <TextBlock Text="Scroll Bar Options" FontSize="12" /> <CheckBox Content="Vertical Scroll Bars" IsThreeState="True" IsChecked="" Checked="cbVerticalScroll_Changed" Unchecked="cbVerticalScroll_Changed" Indeterminate="cbVerticalScroll_Changed" /> <CheckBox Content="Horizontal Scroll Bars" IsThreeState="True" IsChecked="" Checked="cbHorizontalScroll_Changed" Unchecked="cbHorizontalScroll_Changed" Indeterminate="cbHorizontalScroll_Changed"/> </StackPanel> </Border> <Border BorderBrush="Black" BorderThickness="1" Padding="3" Width="180"> <StackPanel> <TextBlock Text="Alternating Row Background" FontSize="12" /> <ComboBox SelectionChanged="cbAltRowBrush_SelectionChanged"> <ComboBoxItem Content="Default" IsSelected="True" /> <ComboBoxItem Content="Custom" /> <ComboBoxItem Content="Null" /> </ComboBox> <TextBlock Text="Row Background" FontSize="12" /> <ComboBox SelectionChanged="cbRowBrush_SelectionChanged"> <ComboBoxItem Content="Default" IsSelected="True" /> <ComboBoxItem Content="Custom" /> <ComboBoxItem Content="Null" /> </ComboBox> <TextBlock Text="Header Visibility" FontSize="12" /> <ComboBox SelectionChanged="cbHeaders_SelectionChanged"> <ComboBoxItem Content="All"/> <ComboBoxItem Content="Column (Default)" IsSelected="True"/> <ComboBoxItem Content="Row"/> <ComboBoxItem Content="None"/> </ComboBox> <TextBlock Text="Grid Lines Visibility" FontSize="12" /> <ComboBox SelectionChanged="cbGridLines_SelectionChanged"> <ComboBoxItem Content="All"/> <ComboBoxItem Content="Vertical (Default)" IsSelected="True"/> <ComboBoxItem Content="Horizontal"/> <ComboBoxItem Content="None"/> </ComboBox> <TextBlock Text="Custom Grid Lines" FontSize="12" /> <CheckBox Content="Vertical" Checked="cbCustomGridLineVert_Changed" Unchecked="cbCustomGridLineVert_Changed"/> <CheckBox Content="Horizontal" Checked="cbCustomGridLineHorz_Changed" Unchecked="cbCustomGridLineHorz_Changed"/> </StackPanel> </Border> </StackPanel> </StackPanel>
Setting the DataGrid Properties in Code
Next, you will add code to handle changes to the user interface controls and set DataGrid properties.
To set DataGrid properties in code
Open MainPage.xaml.vb or MainPage.xaml.cs.
After the MainPage class constructor, add the following code.
This code handles change events for the DataGrid options user interface controls that you added in the previous section. When an option is changed, the corresponding DataGrid property is set.
' READ ONLY Private Sub cbReadOnly_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then Me.dataGrid1.IsReadOnly = cb.IsChecked End If End Sub ' FREEZE COLUMN Private Sub cbFreezeColumn_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then If cb.IsChecked = True Then Me.dataGrid1.FrozenColumnCount = 1 ElseIf cb.IsChecked = False Then Me.dataGrid1.FrozenColumnCount = 0 End If End If End Sub ' HIDE COLUMN Private Sub cbHideColumn_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then If cb.IsChecked = True Then Me.dataGrid1.Columns(0).Visibility = Windows.Visibility.Collapsed ElseIf cb.IsChecked = False Then Me.dataGrid1.Columns(0).Visibility = Windows.Visibility.Visible End If End If End Sub ' SELECTION MODE Private Sub cbSelectionMode_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then If cb.IsChecked = True Then Me.dataGrid1.SelectionMode = DataGridSelectionMode.Single ElseIf cb.IsChecked = False Then Me.dataGrid1.SelectionMode = DataGridSelectionMode.Extended End If End If End Sub ' COLUMN OPTIONS Private Sub cbColReorder_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then Me.dataGrid1.CanUserReorderColumns = cb.IsChecked End If End Sub Private Sub cbColResize_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then Me.dataGrid1.CanUserResizeColumns = cb.IsChecked End If End Sub Private Sub cbColSort_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then Me.dataGrid1.CanUserSortColumns = cb.IsChecked End If End Sub ' SCROLL BARS VISIBILITY Private Sub cbVerticalScroll_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then If cb.IsChecked = True Then Me.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Visible ElseIf cb.IsChecked = False Then Me.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden Else Me.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Auto End If End If End Sub Private Sub cbHorizontalScroll_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then If cb.IsChecked = True Then Me.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible ElseIf cb.IsChecked = False Then Me.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden Else Me.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto End If End If End Sub ' ROW BRUSH Private Sub cbAltRowBrush_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As ComboBox = sender Dim cbi As ComboBoxItem = cb.SelectedItem If Me.dataGrid1 IsNot Nothing Then If cbi.Content.ToString() = "Custom" Then Me.dataGrid1.AlternatingRowBackground = New SolidColorBrush(Color.FromArgb(255, 130, 175, 200)) ElseIf cbi.Content.ToString() = "Default" Then Me.dataGrid1.AlternatingRowBackground = New SolidColorBrush(Color.FromArgb(37, 233, 238, 244)) ElseIf cbi.Content.ToString() = "Null" Then Me.dataGrid1.AlternatingRowBackground = Nothing End If End If End Sub Private Sub cbRowBrush_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As ComboBox = sender Dim cbi As ComboBoxItem = cb.SelectedItem If Me.dataGrid1 IsNot Nothing Then If cbi.Content.ToString() = "Custom" Then Me.dataGrid1.RowBackground = New SolidColorBrush(Color.FromArgb(255, 135, 185, 195)) ElseIf cbi.Content.ToString() = "Default" Then Me.dataGrid1.RowBackground = New SolidColorBrush(Color.FromArgb(0, 255, 255, 255)) ElseIf cbi.Content.ToString() = "Null" Then Me.dataGrid1.RowBackground = Nothing End If End If End Sub ' HEADERS VISIBILITY Private Sub cbHeaders_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As ComboBox = sender Dim cbi As ComboBoxItem = cb.SelectedItem If Me.dataGrid1 IsNot Nothing Then If cbi.Content.ToString() = "All" Then Me.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.All ElseIf cbi.Content.ToString() = "Column (Default)" Then Me.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.Column ElseIf cbi.Content.ToString() = "Row" Then Me.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.Row Else Me.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.None End If End If End Sub ' GRIDLINES VISIBILITY Private Sub cbGridLines_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As ComboBox = sender Dim cbi As ComboBoxItem = cb.SelectedItem If Me.dataGrid1 IsNot Nothing Then If cbi.Content.ToString() = "All" Then Me.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.All ElseIf cbi.Content.ToString() = "Vertical (Default)" Then Me.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.Vertical ElseIf cbi.Content.ToString() = "Horizontal" Then Me.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.Horizontal Else Me.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.None End If End If End Sub ' CUSTOM GRIDLINES Private Sub cbCustomGridLineVert_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then If cb.IsChecked = True Then Me.dataGrid1.VerticalGridLinesBrush = New SolidColorBrush(Colors.Blue) ElseIf cb.IsChecked = False Then Me.dataGrid1.VerticalGridLinesBrush = New SolidColorBrush(Color.FromArgb(255, 223, 227, 230)) End If End If End Sub Private Sub cbCustomGridLineHorz_Changed(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cb As CheckBox = sender If Me.dataGrid1 IsNot Nothing Then If cb.IsChecked = True Then Me.dataGrid1.HorizontalGridLinesBrush = New SolidColorBrush(Colors.Blue) ElseIf cb.IsChecked = False Then Me.dataGrid1.HorizontalGridLinesBrush = New SolidColorBrush(Color.FromArgb(255, 223, 227, 230)) End If End If End Sub
// READ ONLY private void cbReadOnly_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) this.dataGrid1.IsReadOnly = (bool)cb.IsChecked; } // FREEZE COLUMN private void cbFreezeColumn_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) { if (cb.IsChecked == true) this.dataGrid1.FrozenColumnCount = 1; else if (cb.IsChecked == false) this.dataGrid1.FrozenColumnCount = 0; } } // HIDE COLUMN private void cbHideColumn_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) { if (cb.IsChecked == true) this.dataGrid1.Columns[0].Visibility = Visibility.Collapsed; else if (cb.IsChecked == false) this.dataGrid1.Columns[0].Visibility = Visibility.Visible; } } // SELECTION MODE private void cbSelectionMode_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) { if (cb.IsChecked == true) this.dataGrid1.SelectionMode = DataGridSelectionMode.Single; else if (cb.IsChecked == false) this.dataGrid1.SelectionMode = DataGridSelectionMode.Extended; } } // COLUMN OPTIONS private void cbColReorder_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) this.dataGrid1.CanUserReorderColumns = (bool)cb.IsChecked; } private void cbColResize_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) this.dataGrid1.CanUserResizeColumns = (bool)cb.IsChecked; } private void cbColSort_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) this.dataGrid1.CanUserSortColumns = (bool)cb.IsChecked; } // SCROLL BARS VISIBILITY private void cbVerticalScroll_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) { if (cb.IsChecked == true) this.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Visible; else if (cb.IsChecked == false) this.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden; else this.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; } } private void cbHorizontalScroll_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) { if (cb.IsChecked == true) this.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible; else if (cb.IsChecked == false) this.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden; else this.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto; } } // ROW BRUSH private void cbAltRowBrush_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem; if (this.dataGrid1 != null) { if (cbi.Content.ToString() == "Custom") this.dataGrid1.AlternatingRowBackground = new SolidColorBrush(Color.FromArgb(255, 130, 175, 200)); else if (cbi.Content.ToString() == "Default") this.dataGrid1.AlternatingRowBackground = new SolidColorBrush(Color.FromArgb(37, 233, 238, 244)); else if (cbi.Content.ToString() == "Null") this.dataGrid1.AlternatingRowBackground = null; } } private void cbRowBrush_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem; if (this.dataGrid1 != null) { if (cbi.Content.ToString() == "Custom") this.dataGrid1.RowBackground = new SolidColorBrush(Color.FromArgb(255, 135, 185, 195)); else if (cbi.Content.ToString() == "Default") this.dataGrid1.RowBackground = new SolidColorBrush(Color.FromArgb(00, 255, 255, 255)); else if (cbi.Content.ToString() == "Null") this.dataGrid1.RowBackground = null; } } // HEADERS VISIBILITY private void cbHeaders_SelectionChanged(object sender, RoutedEventArgs e) { ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem; if (this.dataGrid1 != null) { if (cbi.Content.ToString() == "All") this.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.All; else if (cbi.Content.ToString() == "Column (Default)") this.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.Column; else if (cbi.Content.ToString() == "Row") this.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.Row; else this.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.None; } } // GRIDLINES VISIBILITY private void cbGridLines_SelectionChanged(object sender, RoutedEventArgs e) { ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem; if (this.dataGrid1 != null) { if (cbi.Content.ToString() == "All") this.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.All; else if (cbi.Content.ToString() == "Vertical (Default)") this.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.Vertical; else if (cbi.Content.ToString() == "Horizontal") this.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.Horizontal; else this.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.None; } } // CUSTOM GRIDLINES private void cbCustomGridLineVert_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) { if (cb.IsChecked == true) this.dataGrid1.VerticalGridLinesBrush = new SolidColorBrush(Colors.Blue); else this.dataGrid1.VerticalGridLinesBrush = new SolidColorBrush(Color.FromArgb(255, 223, 227, 230)); } } private void cbCustomGridLineHorz_Changed(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; if (this.dataGrid1 != null) { if (cb.IsChecked == true) this.dataGrid1.HorizontalGridLinesBrush = new SolidColorBrush(Colors.Blue); else this.dataGrid1.HorizontalGridLinesBrush = new SolidColorBrush(Color.FromArgb(255, 223, 227, 230)); } }
Build and run the application.
When the application runs, you will see a DataGrid that displays the tasks in the taskList collection. In addition, you will see options for dynamically modifying the appearance and behavior of the DataGrid control.
While the application is running, change various options and view the effect on the appearance and behavior of the DataGrid control.
Next Steps
You typically set DataGrid properties in XAML if you do not have to set them dynamically at run time. To see the XAML syntax to set a property, see the XAML Attribute Usage section of the DataGrid property's documentation.
You can also customize a DataGrid by applying styles and templates to the control. Styles and templates enable more customization of the control than is allowed by setting properties. To learn more about how to apply styles and templates to a control, see Control Customization and DataGrid Styles and Templates.
See Also