Skip navigation

Columns & Rows: Part II

Silverlight 2.0 DataGrid Columns

asp:Feature

LANGUAGES: C#

ASP.NET VERSIONS: 3.5

Columns & Rows: Part II

Silverlight 2.0 DataGrid Columns

By Bilal Haidar

Having a Silverlight DataGrid control displaying its columns in an auto-generated fashion does not satisfy most developers. Rather, it is usually the case that developers require in-depth control over the DataGrid columns to decide what to show, what to hide, and even to customize the appearance of the columns.

The Silverlight DataGrid gives developers the opportunity to manipulate and configure its columns in an easy and flexible way. Several built-in columns ship with Silverlight out of the box and within the DataGrid control to help in the customization process.

You were introduced to the DataGrid s major properties in the first installment of this series properties you can use to configure the appearance and behavior of the DataGrid (see the June issue of asp.netPRO). In this article, you ll be introduced to using the DataGrid with column auto-generation, learning how to add a DataGrid control to a User Control page with columns being auto-generated. You ll be introduced to the built-in columns available for you to use out of the box . You ll also learn how to define DataGrid columns in XAML. And, finally, you ll learn how to add at runtime a DataGrid control, together with its columns.

References to Silverlight 2.0

This article assumes you have a fair knowledge of using Silverlight 2.0, especially data-binding features, and is not intended to explain how to use Silverlight 2.0. If you feel you need more information on Silverlight 2.0, it is recommended you check the official website of Silverlight at www.silverlight.net (it contains dozens of articles and videos). Another major resource to learn Silverlight 2.0 is www.silverlightshow.net. This website focuses on delivering rich and comprehensive tutorials covering Silverlight. In addition, you can download from www.microsoft.com/Downloads/details.aspx?familyid=BCE7684A-507B-4FC6-BC99-6933CD690CAB&displaylang=en the Microsoft Silverlight 2 SDK Documentation that covers all the features of Silverlight.

Simple DataGrid

This article follows a step by step approach to present the DataGrid control and its defined columns. To start, we ll add a simple DataGrid control and bind it to some data. Figure 1 shows the XAML used to add a DataGrid control.

The XAML in Figure 1 shows the custom namespace defined at the User Control header definition. As mentioned in Part I, the DataGrid control is part of the Silverlight 2.0 Software Development Kit (SDK), and must be imported to this User Control. The data namespace alias is used whenever you add a DataGrid control to the page, as a way to note to the XAML compiler that the DataGrid control is defined within a different namespace than that of the current User Control.

AutoGenerateColumns="True"

IsReadOnly="True"

HeadersVisibility="Column"

RowBackground="Beige"

AlternatingRowBackground="AliceBlue"

SelectionMode="Single"

GridLinesVisibility="Horizontal"

ColumnWidth="SizeToHeader"

ItemsSource="{Binding}">

Figure 1: Simple DataGrid control

 

Defining a DataGrid control instance is as simple as defining the control with the x:Name only. However, the DataGrid in Figure 1 configures a few major properties, like:

         IsReadOnly: When set to false, the user can double-click any cell and edit its value; however, having its value set to true makes the entire DataGrid read-only, without allowing any cell editing.

         AutoGenerateColumns: This property tells the DataGrid whether to auto-generate the columns based on the data source being bound to it when this property is set to true, or whether the DataGrid control should expect column definitions when the value of this property is set to false.

The rest of the properties were discussed in Part I of this series. Running the Silverlight application displays the diagram shown in Figure 2.

Figure 2

Figure 2: DataGrid with auto generated columns

The DataGrid control shown in Figure 1 is bound to the data source in the code-behind as follows:

this.dgEmployees.DataContext =

EmployeeManager.GetEmployeeList();

The EmployeeManager.GetEmployeeList method is a simple method that returns a collection of Employee objects to be displayed in the DataGrid. To bind the DataGrid control to a data source, use either of these properties:

         ItemsSource: You set the ItemsSource property to an IEnumerable implementation. Examples are List, ObservableCollection, and other collections. In the code-behind you bind to the ItemsSource property.

         DataContext: You set the ItemsSource property to the Binding extension markup {Binding} value. In the code-behind you simply bind on the DataContext property and not the ItemsSource property.

Once you bind the DataGrid control to a data source, each object in the bound collection will be represented by one row, and every property on the bound object will be represented by a column, as in the case of AutoGeneratedColumns=true .

DataGrid Built-in Columns

The DataGrid control ships with three built-in columns that help the developer customize the data displayed by the DataGrid. The built-in columns are:

         DataGridTextColumn: The DataGridTextColumn is the default, and simplest column type. By default, when the AutoGeneratedColumns property of the DataGrid is set to true, the DataGrid control uses the DataGridTextColumn to represent all the data bound object s properties (except those of Boolean values). In the read-only mode, the DataGridTextColumn uses a TextBlock control to represent the underlying data source object s property value. While in edit mode, a TextBox control is used to display the data, allowing the use of inline editing. For more detailed information, visit msdn.microsoft.com/en-us/library/system.windows.controls.datagridtextcolumn(VS.95).aspx.

         DataGridCheckBoxColumn: The DataGridCheckBoxColumn is used by the DataGrid control to represent Boolean values, in the underlying data source, as a CheckBox control. This means that if you have a property in the object that is of type Boolean, that property will be displayed inside the DataGrid control as a CheckBox control. For more detailed information, visit msdn.microsoft.com/en-us/library/system.windows.controls.datagridcheckboxcolumn(VS.95).aspx.

         DataGridTemplateColumn: The DataGridTemplateColumn is the most flexible and popular DataGrid column. In some cases you might feel unsatisfied with the other two built-in columns, and thus feel the need for a flexible way to define new column types. For such cases, the DataGridTemplateColumn is used. For the read-only state, set the CellTemplate property to any UI with which you want to display the underlying data. In the case of editing state, set the CellEditingTemplate property to the UI to show when the DataGrid s row is in edit mode. For more detailed information, visit msdn.microsoft.com/en-us/library/system.windows.controls.datagridtemplatecolumn(VS.95).aspx.

Now that you know the different column types available, let s have a look at some of the major properties each column holds.

Common Properties

Some properties are shared among all the columns previously cited:

         CanUserReorder: Allows/Prevents user from reordering the column. The value set at the column level overrides the one set at the DataGrid level.

         CanUserResize: Allows/Prevents user from resizing the column. The value set at the column level overrides the one set at the DataGrid level.

         CanUserSort: Allows/Prevents user from clicking on the column to sort the data accordingly. The value set at the column level overrides the one set at the DataGrid level.

         Header: Allows setting a header text for the column.

         IsFrozen: If this is true , the specified column will be frozen and outside the range of the horizontal scrollbar.

         IsReadOnly: When set to true , the column is always displayed as read-only. Double-clicking the column in this case will not enter the row into the editing mode. When this property is set both at the DataGrid level and column level, the true value always wins.

         MaxWidth: This property specifies the maximum width a column can reach.

         MinWidth: This property specifies the minimum width a column can reach.

         SortMemberPath: By default in the DataGridTextColumn and DataGridCheckBoxColumn, this property is set to the bounding property on the column. In the case of DataGridTemplateColumn, this property must be set to enable sorting on the template column.

         Visibility: This property controls the visibility of the column.

         Width: This property sets the width of the column. This property is of type GridLength, which helps in auto-sizing the column. It can be any of the following values:

o    SizeToHeader: This value auto-sizes the width of the cell to that of the header column cell.

o    SizeToCells: This value auto-sizes the width of the cell to the largest cell showing in the same column, ignoring the header column cell width.

o    Numeric: This value specifies the exact width as a double value.

o    Auto: This is a combination of the SizeToHeader and SizeToCells values. With this value, the cell s width would auto-size to the header column cell width, or to the largest cell width.

DataGridTextColumn. The DataGridTextColumn has a few properties of its own:

         FontFamily: Allows you to set the font family of the cell s content.

         FontSize: Allows you to set the font size of the cell s content.

         FontStyle: Allows you to set the font style of the cell s content.

         FontWeight: Allows you to set the font weight of the cell s content.

         Foreground: Allows you to set the foreground color of the cell s content.

DataGridCheckBoxColumn. The DataGridCheckBoxColumn has a single, specific property:

         IsThreeState: This property decides whether the underlying CheckBox control allows three or two states. In addition to Checked and Unchecked, the CheckBox can have a null state, which happens when you bind the CheckBox control to a null value when its IsThreeState property is enabled.

DataGridTemplateColumn. The DataGridTemplateColumn has two main specific properties:

         CellTemplate: You set this property to a DataTemplate to control how to display the data in this custom cell when the row is in read-only mode.

         CellEditingTemplate: You set this property to a DataTemplate to control how to display the data in this custom cell when the row is in edit mode.

In the coming sections you ll see how to use the above columns to customize the display of data using the DataGrid control.

DataGrid XAML-defined Columns

In this section of the article, we ll look at how to add a DataGrid control to a User Control and define its columns explicitly. Figure 3 shows a DataGrid control definition.

Binding="{Binding Path=FirstName}"

CanUserReorder="False" CanUserResize="True"

CanUserSort="True" IsReadOnly="True"

Width="100" Header="First Name">

Binding="{Binding Path=LastName}"

Width="100" Visibility="Collapsed"

Header="Last Name">

Binding="{Binding Path=IsMarried}" Header="Is Married?"

Visibility="Visible" IsThreeState="True" />

ItemsSource="{Binding Path=MemberOf, Mode=OneTime}"

BorderThickness="0" Background="Transparent" />

Figure 3: DataGrid with XAML-defined columns

 

To define DataGrid columns, simply use the Columns property on the DataGrid by using the property element syntax. The Columns property holds a collection of columns.

The first column is defined as a DataGridTextColumn as follows:

Binding="{Binding Path=FirstName}"

CanUserReorder="False" CanUserResize="True"

CanUserSort="True" IsReadOnly="True"

Width="100" Header="First Name">

The Binding property is set to the bound object s property; in this case, FirstName . Other common properties are set, like the CanUserReorder, CanUserResize, CanUserSort, IsReadOnly, Width, and Header.

The above column makes use of the ElementStyle property, which can be used to edit the Style of the cell displayed.

The second column defined also is a DataGridTextColumn, and is similar to the above column; however, its Visibility property is set to Collapsed , which means the column will be hidden.

The third column is defined as a DataGridCheckBoxColumn:

IsThreeState="True" />

Defining a DataGridCheckBoxColumn is as simple as adding the column definition and configuring a few properties on the corresponding column (as shown above).

Notice in Figure 2 the MemberOf column. This column corresponds to a property on the data source object that is of type List. When the columns are auto-generated, this column is bound automatically to the ToString method on the List instance. Hence, you see the 'System.Collections.Generic.List'1[[System.String] value in the cell, instead of the real items of the MemberOf collection.

A DataGridTemplateColumn is needed to solve this problem, as shown in the MemberOf column here:

ItemsSource="{Binding Path=MemberOf, Mode=OneTime}"

BorderThickness="0" Background="Transparent" />

 

When you add a DataGridTemplateColumn, the important thing to define is the CellTemplate. The CellTemplate is set to a DataTemplate that defines the UI of the cell. In this case, the DataTemplate defines a ListBox control to list all the entries of the bounding property, the MemberOf collection.

DataGrid Columns at Runtime

Now that you ve seen how to define columns inside XAML, it s time to see how we can accomplish the same thing at runtime or through code.

The following code shows how to define the DataGrid control and specify its columns using code-behind. Start by creating a new instance of the DataGrid control:

DataGrid gdEmployees = new DataGrid();

Configure some properties and the data source:

gdEmployees.AutoGenerateColumns = false;

gdEmployees.ItemsSource =

EmployeeManager.GetEmployeeList();

gdEmployees.IsReadOnly = false;

Add the DataGrid instance to the User Control; in this case, the DataGrid is added as a child control into the User Control s Grid layout panel:

this.LayoutRoot.Children.Add(gdEmployees);

Start adding a few columns and adding some major properties to them:

DataGridTextColumn jobTitle =

new DataGridTextColumn();

jobTitle.Header = "Job Title";

jobTitle.Binding = new Binding("JobTitle");

jobTitle.IsReadOnly = true;

Add into the DataGrid s Column collection the column created:

gdEmployees.Columns.Add(jobTitle);

Another column is added of type DataGridCheckBoxColumn:

DataGridCheckBoxColumn isMarried =

new DataGridCheckBoxColumn();

isMarried.Binding = new Binding("IsMarried");

isMarried.Header = "Is Married?";

isMarried.IsThreeState = true;

gdEmployees.Columns.Add(isMarried);

As you can see, creating a DataGrid at runtime and defining its columns is as simple as creating it through XAML-defined columns.

There are additional major properties that can be manipulated on the DataGrid control. The code download accompanying this article explores additional important properties; take some time to explore how they are implemented. I also suggest you visit bhaidar.net/SilverlightDataGrid/GridColumns.aspx to browse a live sample and play around with all the major DataGrid properties.

In addition, you can download the accompanying solution code for this article and open it in Visual Studio 2008. This will help you browse all the DataGrid properties that were not tackled in this article, yet are covered in the accompanying code. If Visual Studio gives the following error upon opening the code solution:

The project type is not supported by this installation.

all you need to do is reinstall on your machine the Visual Web Developer of the current installation of Visual Studio 2008.

Conclusion

This article provides an overview to the built-in DataGrid columns that ship with Silverlight 2.0. It goes deeper by experimenting with defining DataGrid columns at the XAML level and at runtime through code.

Source code accompanying this article is available for download.

Bilal Haidar ([email protected]) is a Microsoft MVP in ASP.NET. He is an MCP, MCTS, MCPD, MCT, and Telerik MVP. He is a lead software developer at CCC, a multinational construction company based in Athens, Greece.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish