7

I want a specific template for all my columns in DataGrid. The usual method is I will replicate the entire XAML for DataTemplate multiple times in the DataGrid in each of the Column.

Is there any way I can define the CellTemplate globally as a resource and then just pass the the "Path" property of "Binding" to it, so that it displays the correct item from the DataContext ?

Is this possible ?

Revious
  • 7,816
  • 31
  • 98
  • 147
teenup
  • 7,459
  • 13
  • 63
  • 122
  • Markup Extension, in a hacky way may be the solution. Check [this answer](http://stackoverflow.com/a/23106619/2279200), which originates from [this answer](http://stackoverflow.com/a/7170525/2279200) – Athafoud Oct 21 '16 at 09:09

1 Answers1

7

Create DataTemplate in App.Xaml file with key/name.

 <DataTemplate x:Name="myTemplate" TargetType="sdk:DataGridTemplateColumn">
                <StackPanel Orientation="Horizontal">
                    <TextBox Text="{Binding FirstName}" BorderThickness="0"/>
                    <TextBox Text="{Binding LastName}" BorderThickness="0"/>
                </StackPanel>
  </DataTemplate>

Now you can use this template in DataGrid like

 <sdk:DataGridTemplateColumn Header="Name" CellTemplate={StaticResource myTemplate}>

OR
You can to pass Binding Path name in code behind like...

        string colPath = "FirstName";
        DataGrid grid = new DataGrid();
        grid.ItemsSource = myViewModel.EmpCollection;

        DataGridTemplateColumn column = new DataGridTemplateColumn();
        DataTemplate itemTemplate = (DataTemplate)XamlReader.Load("<DataTemplate xmlns=\"http://schemas.microsoft.com/client/2007\"> <ContentPresenter Content=\"{Binding Path=" + colPath + "}\"  /></DataTemplate>");

        column.CellTemplate = itemTemplate;
        grid.Columns[0] = column;

Hope this will help.

dipak
  • 2,011
  • 2
  • 17
  • 24
  • I need to pass the Binding Path into DataTemplate from actual DataGridTemplateColumn, otherwise there will be a need of 7 different DataTemplates for having 7 columns in DataGrid, which is no better than writing 7 times the same XAML. Here, in your example, I need to pass FirstName somewhere from actual TemplateColumn and it should be available in DataTemplate. – teenup Dec 02 '11 at 17:56
  • Hi Punit, if you can use Code behind to add DataGrid or assign column to your datagrid then I think you are fine to do it. – dipak Dec 03 '11 at 18:32
  • Actually, I was looking for a XAML solution, I knew I can do it like this in code behind. Anyways, because there are no responses, I believe we can not do it in XAML as of now. – teenup Dec 05 '11 at 09:35