5

I need to create a common DataGridTemplateColumn, so that I can use it across my application with different objects and properties.

here is some sample code, I use in my project

<DataGridTemplateColumn Width="100*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Age}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>   
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Path=Age}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

I need a generic version of the code so that I can place the DataTemplate in app.xaml and reference it in my code

Athafoud
  • 2,898
  • 3
  • 40
  • 58
Jagan
  • 81
  • 1
  • 1
  • 3
  • Possible duplicate of [Can I define CellTemplate of DataGrid as a Resource so that it can be reused in multiple columns?](http://stackoverflow.com/questions/8354650/can-i-define-celltemplate-of-datagrid-as-a-resource-so-that-it-can-be-reused-in) – Athafoud Oct 21 '16 at 09:00

1 Answers1

8

You can't template DataGridTemplateColumn directly. But fortunately you can use global templates for cells. Take a look at example:

App.xaml

<Application.Resources>

    <DataTemplate x:Key="CellEdintingTemplate">
        <TextBox Text="{Binding Path=Age}" />
    </DataTemplate>
    <DataTemplate x:Key="CellTemplate">
        <TextBlock Text="{Binding Path=Age}" />
    </DataTemplate>

</Application.Resources>

Using

    <DataGrid>
        <DataGrid.Columns>
            <DataGridTemplateColumn 
                 CellEditingTemplate="{StaticResource CellEdintingTemplate}" 
                 CellTemplate="{StaticResource CellTemplate}" />
        </DataGrid.Columns>
    </DataGrid>
asktomsk
  • 2,289
  • 16
  • 23