Click here to Skip to main content
15,867,835 members
Articles / Desktop Programming / WPF

WPF Toolkit DataGrid Supporting Multiple Column Sets

Rate me:
Please Sign up or sign in to vote.
4.80/5 (5 votes)
12 Jul 2010CPOL2 min read 53.5K   1.3K   21   5
WPF Toolkit DataGrid supporting multiple column sets

Introduction

The WPF Toolkit's DataGrid is a powerful grid control allowing to format data in various ways.

In my application, I wanted the user to be able to control which data he gets displayed in the DataGrid. To do so, he can open an options dialog and choose between some radio buttons. Each radio button defines a set of data columns displayed in the DataGrid.

While it is possible to define multiple column sets by code (DataGrid.Columns property), the DataGrid only allows to define one column set via XAML.

The MultiColSetDataGrid control described in this article helps to overcome this limitation.

Background

The class MultiColSetDataGrid has a property ColumnsDefinitionList containing a list of column sets and a property RowDetailsTemplateList containing a list of DataTemples displayed in the row details area.

A further property GridColumnsDefinitionsIndex controls which column set and row details DataTemplate is currently set. This property can be databinded by view models.

Using the Code

The MainWindow.xaml file contains the MultiColumnSetDataGrid control:

C#
<ctrl:MultiColSetDataGrid x:Name="myGrid" 
    ItemsSource="{Binding PersonList}" 
    .... 

The MainWindowVM's (view model) property PersonList is used as ItemsSource. The list is a list of persons. Each entry is of type PersonVM offering FirstName and LastName as String properties.

Two sets of columns are defined in the MainWindow.xaml:

XML
<ctrl:MultiColSetDataGrid.ColumnsDefinitionList>
  <ctrl:ColumnsDefinition>
    <ctrl:ColumnsDefinition.GridColumns>
      <tk:DataGridTextColumn Width="Auto" 
        Header="First Name" 
        Binding="{Binding FirstName}" />
    </ctrl:ColumnsDefinition.GridColumns>
  </ctrl:ColumnsDefinition>
  <ctrl:ColumnsDefinition>
    <ctrl:ColumnsDefinition.GridColumns>
      <tk:DataGridTextColumn Width="Auto" 
        Header="First Name" 
        Binding="{Binding FirstName}" />
      <tk:DataGridTextColumn Width="Auto" 
        Header="Last Name" 
        Binding="{Binding LastName}" />
    </ctrl:ColumnsDefinition.GridColumns>
  </ctrl:ColumnsDefinition>
</ctrl:MultiColSetDataGrid.ColumnsDefinitionList>        

Two DataTemplates are defined for the row details section:

XML
<ctrl:MultiColSetDataGrid.RowDetailsTemplateList>
  <DataTemplate>
    <StackPanel Orientation="Horizontal" Margin="20,0,0,0">
      <TextBlock Text="Name: " FontWeight="Bold"/>
      <TextBlock Text="{Binding FirstName}"/>
    </StackPanel>
  </DataTemplate>
  <DataTemplate>
    <StackPanel Orientation="Horizontal" Margin="20,0,0,0">
      <TextBlock Text="Name: " FontWeight="Bold"/>
      <TextBlock Text="{Binding LastName}"/>
      <TextBlock Text=", "/>
      <TextBlock Text="{Binding FirstName}"/>
    </StackPanel>
  </DataTemplate>
</ctrl:MultiColSetDataGrid.RowDetailsTemplateList>

A button is used to switch between the column sets:

XML
<Button Width="120" Command="{Binding CmdSwitch}" Content="Switch Column Sets" /> 

The MainWindowVM has an integer property CurrentColumnSetIndex, which determines the column set currently used. This property is binded to the MultiColumnSetDataGrid's dependency property GridColumnsDefinitionsIndex.

C#
<ctrl:MultiColSetDataGrid x:Name="myGrid" 
    ...
    GridColumnsDefinitionsIndex="{Binding CurrentColumnSetIndex, Mode=TwoWay}"> 

The ViewModel's ICommand bound to the button switches the CurrentColumnSetIndex value from 0 to 1 and vice versa.

C#
public ICommand CmdSwitch
{
  get
  {
    return new RelayCommand(p => DoSwitch());
  }
}

private void DoSwitch()
{
  if (this.CurrentColumnSetIndex == 0)
    this.CurrentColumnSetIndex = 1;
  else
    this.CurrentColumnSetIndex = 0;
} 

The setter of MultiColSetDataGrid's property GridColumnsDefinitionsIndex is called via databinding and calls method LoadColumns...

C#
public Int32 GridColumnsDefinitionsIndex
{
  get
  {
    return (Int32)this.GetValue(GridColumnsDefinitionsIndexProperty);
  }
  set
  {
    this.SetValue(GridColumnsDefinitionsIndexProperty, value);
    LoadColumns();
  }
}

And in method LoadColumns the defined column set behind the index is loaded:

C#
private void LoadColumns()
{
  int tmpIndex = this.GridColumnsDefinitionsIndex;
  if (this.ColumnsDefinitionList == null || tmpIndex < 0 || 
		tmpIndex >= this.ColumnsDefinitionList.Count)
    return;

  // Load column set
  List<DataGridColumn> tmpColumns = 
		this.ColumnsDefinitionList[tmpIndex].GridColumns;
  this.Columns.Clear();
  foreach (var tmpColumn in tmpColumns)
    this.Columns.Add(tmpColumn);

  // Set RowDetailsTemplate
  if (this.RowDetailsTemplateList == null || tmpIndex < 0 || 
		tmpIndex >= this.RowDetailsTemplateList.Count)
    return;
  this.RowDetailsTemplate = this.RowDetailsTemplateList[tmpIndex];
}

The following screenshot shows the application after startup containing the column set with index 0 displaying the "First Name" column only:

grid_with_1_column.jpg

The following screenshot shows the application after having clicked on the "Switch column sets" button. The grid is displaying the"First Name" and "Last Name" columns:

grid_with_2_cols.jpg

History

  • Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Tamil Selvan K3-Jul-12 3:54
Tamil Selvan K3-Jul-12 3:54 
Questionvery nice Pin
BillW337-Nov-11 9:19
professionalBillW337-Nov-11 9:19 
Generalconvert to VS2008 Pin
toilaleanh28-Jan-11 3:19
toilaleanh28-Jan-11 3:19 
GeneralGreat solution Pin
granty22-Sep-10 17:48
granty22-Sep-10 17:48 
I like your solution to this problem.

My view sets the datacontext via XAML and this causes a problem for your control in that the GridColumnsDefinitionsIndex is set before the columns are defined.
This means that LoadColumns never gets to transfer the columns from the GridColumns collection to the datagrid columns collection.

I've got this working by changing ColumnsDefinitionList from a List to an ObservableCollection and monitoring its CollectionChanged event.
In response to the CollectionChanged event I just call LoadColumns();

I've made a couple of other minor changes to the class that may be of use.

1. Moved the call to LoadColumns from the GridColumnsDefinitionsIndex property set method to OnGridColumnsDefinitionsIndexChanged.
2. Removed tmpGrid.GridColumnsDefinitionsIndex = (Int32)e.NewValue; from OnGridColumnsDefinitionsIndexChanged. I think you only needed this because the call to LoadColumns was in the "wrong" place.
GeneralMy vote of 5 Pin
tripathy.rajendra@gmail.com21-Sep-10 21:31
tripathy.rajendra@gmail.com21-Sep-10 21:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.