Can I define a CellTemplate DataGrid as a resource so that it can be reused across multiple columns?

I need a specific template for all my columns in a DataGrid. Normal method: I will replicate the entire XAML for the DataTemplate several times in the DataGrid in each column.

Is there any way to define a CellTemplate globally as a resource, and then just pass the “Path” property to “Binding” so that it displays the correct element from the DataContext?

Is it possible?

+4
source share
1 answer

Create a DataTemplate in the App.Xaml file with the 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 a DataGrid, for example

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

OR
   , ...

        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;

, .

+4

All Articles