在WPF中创建通用的DataGridTemplateColumn

5
我需要创建一个通用的DataGridTemplateColumn,以便我可以在整个应用程序中使用它来处理不同的对象和属性。
以下是我在项目中使用的一些示例代码。
<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>

我需要一个通用版本的代码,这样我就可以将 DataTemplate 放在 app.xaml 中,并在我的代码中引用它。


1个回答

8
您不能直接对DataGridTemplateColumn进行模板化。但是,您可以为单元格使用全局模板。请看以下示例: 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>

使用

    <DataGrid>
        <DataGrid.Columns>
            <DataGridTemplateColumn 
                 CellEditingTemplate="{StaticResource CellEdintingTemplate}" 
                 CellTemplate="{StaticResource CellTemplate}" />
        </DataGrid.Columns>
    </DataGrid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接