WPF Data Grid - Change a Cell Template Based on Custom Logic

This example demonstrates how to use the CellTemplateSelector property to change a cell template based on a condition.

image

To implement this approach, do the following:

  1. Specify custom DataTemplates. Editors declared in these templates should follow our recommendations from this help topic: CellTemplate:

    <DataTemplate x:Key="booleanEditor">
        <dxe:CheckEdit Name="PART_Editor" />
    </DataTemplate>
    <DataTemplate x:Key="buttonEditor">
        <dxe:ButtonEdit Name="PART_Editor" />
    </DataTemplate>
    <DataTemplate x:Key="comboboxEditor">
        <dxe:ComboBoxEdit Name="PART_Editor" .../>
    </DataTemplate>
    <DataTemplate x:Key="dateEditor">
        <dxe:DateEdit Name="PART_Editor" />
    </DataTemplate>
    <DataTemplate x:Key="textEditor">
        <dxe:TextEdit Name="PART_Editor" />
    </DataTemplate>
  2. Create a custom DataTemplateSelector descendant. This descendant should return templates according to your scenario requirements.

    Note: Each GridControl cell contains an object of the EditGridCellData data type in its DataContext. This object's RowData.Row property contains your data item. You can use this property if your logic should take property values from data items into account:

    public class EditorTemplateSelector : DataTemplateSelector {
        public override DataTemplate SelectTemplate(object item, DependencyObject container) {
            EditGridCellData data = (EditGridCellData)item;
            var dataItem = data.RowData.Row as TestData;
            return dataItem == null || string.IsNullOrEmpty(dataItem.Editor) ? null : (DataTemplate)((FrameworkElement)container).FindResource(dataItem.Editor);
        }
    }

Files to look at

Documentation

More Examples

Does this example address your development requirements/objectives?

(you will be redirected to DevExpress.com to submit your response)