我可以将 DataGrid 的 CellTemplate 定义为 Resource 以便它可以在多个列中重复使用吗? [英] Can I define CellTemplate of DataGrid as a Resource so that it can be reused in multiple columns?

查看:22
本文介绍了我可以将 DataGrid 的 CellTemplate 定义为 Resource 以便它可以在多个列中重复使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个用于 DataGrid 中所有列的特定模板.通常的方法是我将在 DataGrid 中的每个 Column 中多次复制 DataTemplate 的整个 XAML.

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.

有什么方法可以将 CellTemplate 全局定义为资源,然后将绑定"的路径"属性传递给它,以便它显示来自 DataContext 的正确项目?

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 ?

这可能吗?

推荐答案

在 App.Xaml 文件中使用键/名称创建 DataTemplate.

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>

现在你可以在 DataGrid 中使用这个模板了

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;

希望这会有所帮助.

这篇关于我可以将 DataGrid 的 CellTemplate 定义为 Resource 以便它可以在多个列中重复使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆