0

I have the following DataTemplate for displaying the full name of a User instance:

<DataTemplate x:Key="NameCellTemplate">
    <Label HorizontalAlignment="Stretch" Height="25">
        <Label.Content>
            <MultiBinding 
                Converter="{StaticResource FullNameConverter}"
                ConverterParameter="{x:Static Conv:NameFormat.FirstThenLast}" >

                <!-- Requires binding to object of type 'User' -->
                <Binding Path="FirstName" />
                <Binding Path="LastName" />
            </MultiBinding>
        </Label.Content>
    </Label>
</DataTemplate>

I currently use it to customize a template column, like so:

<DataGridTemplateColumn 
    CellTemplate="{StaticResource NameCellTemplate}" />

This column belongs to a data grid full of User instances, but I would like to re-use the data template for a column in a different data grid. This second data grid binds to a different type, which instead keeps User as a property, so I'd like to do this:

<DataGridTemplateColumn 
    Binding="{Binding Path=User}" 
    CellTemplate="{StaticResource NameCellTemplate}" />

However, the Binding attribute isn't permitted for a template column.

How can I specify a binding path for the column template, or modify the data template, such that the data template can be reused for either data grid?

4

1 回答 1

2

在这种情况下,由于 datagrid 行的数据上下文不同,因此您可以像这样应用模板:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentControl Content="{Binding User}" 
                            ContentTemplate="{StaticResource NameCellTemplate}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
于 2013-09-04T18:09:01.540 回答