Skip to main content
A newer version of this page is available. .

Binding to a Collection of Columns

  • 11 minutes to read

When engineering a WPF application using the Model View ViewModel (MVVM) architectural pattern, you may be required to describe columns in a Model or ViewModel. The grid can be bound to a collection of objects containing column settings, described in a Model or ViewModel, thus minimizing the need for ‘code-behind’.

View Model Implementation

Assume an Employee view model. It includes the following classes.

  • Employee - a data object that contains employee information (e.g. first and last names, job title, etc.).
  • ViewModel - the employee view model.
  • EmployeeData - supplies employee information to be displayed within the grid control.
  • Column - describes a grid column. This class provides properties that correspond to settings common to all types of grid columns.
  • ComboBoxColumn - corresponds to a grid column with the ComboBoxEdit in-place editor. This class provides the Source property, which contains the list of a combo box item (in this example, these are cities).
  • SettingsType - enumerates possible types of in-place editors used to edit cell values.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Model {
    public class ViewModel {
        public List<string> Cities { get; private set; }
        // Returns a list of employees so that they can be bound to the grid control.
        public List<Employee> Source { get; private set; }
        // The collection of grid columns.
        public ObservableCollection<Column> Columns { get; private set; }
        public ViewModel() {
            Source = EmployeeData.DataSource;
            List<string> _cities = new List<string>();
            foreach (Employee employee in Source) {
                if (!_cities.Contains(employee.City))
                    _cities.Add(employee.City);
            }
            Cities = _cities;
            Columns = new ObservableCollection<Column>() {
                new Column() { FieldName = "FirstName", Settings = SettingsType.Default },
                new Column() { FieldName = "LastName", Settings = SettingsType.Default },
                new Column() { FieldName = "JobTitle", Settings = SettingsType.Default },
                new Column() { FieldName = "BirthDate", Settings = SettingsType.Default },
                new ComboColumn() { FieldName = "City", Settings = SettingsType.Combo, Source = Cities }
            };
        }
    }
    // The data item.
    public class Employee {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string JobTitle { get; set; }
        public string City { get; set; }
        public DateTime BirthDate { get; set; }
    }
    public class EmployeeData : List<Employee> {
        public static List<Employee> DataSource {
            get {
                List<Employee> list = new List<Employee>();
                list.Add(new Employee() {
                    FirstName = "Nathan",
                    LastName = "White",
                    City = "NY",
                    JobTitle = "Sales Manager",
                    BirthDate = new DateTime(1970, 1, 10)  });
                return list;
            }
        }
    }
    public class Column {
        // Specifies the name of a data source field to which the column is bound.
        public string FieldName { get; set; }
        // Specifies the type of an in-place editor used to edit column values.
        public SettingsType Settings { get; set; }
    }
    // Corresponds to a column with the combo box in-place editor.
    public class ComboColumn : Column {
        // The source of combo box items.
        public IList Source { get; set; }
    }
    public enum SettingsType { Default, Combo }
}

Note

If the Columns collection might be changed after it has been assigned to the grid control, it should implement INotifyCollectionChanged, so that changes made within a View Model are automatically reflected by the grid.

Column Templates and Selector

The Grid Control generates columns based on column templates. Create multiple templates, one template for each column type. Using a single template you can create an unlimited number of columns in unlimited number of grid controls. In this example, there are two column templates: DefaultColumnTemplate and ComboColumnTemplate.

To avoid performance issues when binding to column properties, use the dxci:DependencyObjectExtensions.DataContext attached property. See the example below.

<!---->
xmlns:dxci="http://schemas.devexpress.com/winfx/2008/xaml/core/internal"
<!---->
    <DataTemplate x:Key="DefaultColumnTemplate">
        <ContentControl>
            <dxg:GridColumn FieldName="{Binding Path=(dxci:DependencyObjectExtensions.DataContext).FieldName, RelativeSource={RelativeSource Self}}"
                Header="{Binding Path=(dxci:DependencyObjectExtensions.DataContext).Header, RelativeSource={RelativeSource Self}}"
                Width="{Binding Path=(dxci:DependencyObjectExtensions.DataContext).Width, RelativeSource={RelativeSource Self}}" />
        </ContentControl>
    </DataTemplate>

To choose the required template based on the column’s type, use the Template Selector. In this example, the template selector is represented by the ColumnTemplateSelector class.

<Window x:Class="WpfApplication10.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
        xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
        xmlns:dxci="http://schemas.devexpress.com/winfx/2008/xaml/core/internal"
        xmlns:model="clr-namespace:Model"
        xmlns:view="clr-namespace:View">
    <Window.DataContext>
        <model:ViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <view:ColumnTemplateSelector x:Key="ColumnTemplateSelector"/>
        <DataTemplate x:Key="DefaultColumnTemplate">
            <ContentControl>
                <dxg:GridColumn FieldName="{Binding Path=(dxci:DependencyObjectExtensions.DataContext).FieldName, RelativeSource={RelativeSource Self}}"/>
            </ContentControl>
        </DataTemplate>
        <DataTemplate x:Key="ComboColumnTemplate">
            <ContentControl>
                <dxg:GridColumn FieldName="{Binding Path=(dxci:DependencyObjectExtensions.DataContext).FieldName, RelativeSource={RelativeSource Self}}">
                    <dxg:GridColumn.EditSettings>
                        <dxe:ComboBoxEditSettings ItemsSource="{Binding Source}"/>
                    </dxg:GridColumn.EditSettings>
                </dxg:GridColumn>
            </ContentControl>
        </DataTemplate>
    </Window.Resources>
    <Grid>
    </Grid>
</Window>
using System.Windows;
using System.Windows.Controls;
using Model;

namespace View {
    public class ColumnTemplateSelector : DataTemplateSelector {
        public override DataTemplate SelectTemplate(object item, DependencyObject container) {
            Column column = (Column)item;
            return (DataTemplate)((Control)container).FindResource(column.Settings + "ColumnTemplate");
        }
    }
}

Note

If all grid columns can be described using a single template, you have no need to create a column template selector. Instead, assign this template to the grid’s DataControlBase.ColumnGeneratorTemplate property.

Note

You can create a style to specify settings common to all columns generated using different templates. You can specify bindings to ViewModel properties within a style (see FieldName below):

<Window.Resources>
    <Style x:Key="ColumnStyle" TargetType="dxg:GridColumn">
        <Setter Property="FilterPopupMode" Value="CheckedList"/>
        <Setter Property="FieldName" Value="{Binding Path=(dxci:DependencyObjectExtensions.DataContext).FieldName, RelativeSource={RelativeSource Self}}"/>
    </Style>
</Window.Resources>

This style should be assigned to the DataControlBase.ColumnGeneratorStyle property.

Customizing the WPF DXGrid

Finally, specify the grid’s DataControlBase.ItemsSource, DataControlBase.ColumnsSource and DataControlBase.ColumnGeneratorTemplateSelector. The DataControlBase.ItemsSource property specifies the grid’s data source. The DataControlBase.ColumnsSource property specifies the source from which the grid generates columns. The DataControlBase.ColumnGeneratorTemplateSelector property specifies the column template selector, which returns a template for each column based on its type.

<Grid>
        <dxg:GridControl Name="grid"
                         ItemsSource="{Binding Source}"
                         ColumnsSource="{Binding Columns}"
                         ColumnGeneratorTemplateSelector="{StaticResource ColumnTemplateSelector}">
            <dxg:GridControl.View>
                <dxg:TableView Name="tableView1"
                               AutoWidth="True"
                               NavigationStyle="Cell" />
            </dxg:GridControl.View>
        </dxg:GridControl>
    </Grid>

The image below shows the result.

mvvm-columnbinding-result

Examples

This example shows how to put columns and data summary definition logic in the ViewModel and setup the Grid Control.

View Example

Imports System.Windows.Controls
Imports System.Windows
Imports Model

Namespace GridMVVMBindableColumns
    Partial Public Class MainPage
        Inherits UserControl

        Public Sub New()
            InitializeComponent()
        End Sub
    End Class
End Namespace
See Also