Can I define CellTemplate of DataGrid as a Resource so that it can be reused in multiple columns?

纵饮孤独 提交于 2019-12-03 15:22:54

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!