Export (0) Print
Expand All

Walkthrough: Customizing the DataGrid Control Using Properties

Silverlight

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.

Run this sample

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.

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.

Next, you create a collection of Task objects to be displayed in the DataGrid.

To create a collection of Task objects

  1. Add a class named Task to the DGBasicCustomization project.

  2. 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.

    
    public string Name { get; set; }
    public DateTime DueDate { get; set; }
    public bool Complete { get; set; }
    public string Notes { get; set; }
    
    
    
  3. Open MainPage.xaml.vb or MainPage.xaml.cs.

  4. 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.
    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;
    
    
    

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

  1. 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.

  2. Open MainPage.xaml.

  3. 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="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

  4. In the <UserControl> start tag, change the value of the Width property to 600, and the value of the Height property to 700.

  5. 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>
    
    
    
  6. 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.

Next, you create the user interface for the DataGrid options.

To create the user interface for the DataGrid options

  1. Open MainPage.xaml.

  2. 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>
    
    
    

Next, you will add code to handle changes to the user interface controls and set DataGrid properties.

To set DataGrid properties in code

  1. Open MainPage.xaml.vb or MainPage.xaml.cs.

  2. 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 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));
        }
    }
    
    
    
  3. 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.

  4. While the application is running, change various options and view the effect on the appearance and behavior of the DataGrid control.

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.

Community Additions

ADD
Show:
© 2014 Microsoft