Create Common DataGridTemplateColumn in WPF

时光总嘲笑我的痴心妄想 提交于 2020-01-01 10:58:11

问题


I need to create a common DataGridTemplateColumn, so that I can use it across my application with different objects and properties.

here is some sample code, I use in my project

<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>

I need a generic version of the code so that I can place the DataTemplate in app.xaml and reference it in my code


回答1:


You can't template DataGridTemplateColumn directly. But fortunately you can use global templates for cells. Take a look at example:

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>

Using

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


来源:https://stackoverflow.com/questions/10361122/create-common-datagridtemplatecolumn-in-wpf

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