سؤال

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?

هل كانت مفيدة؟

المحلول

In this case as the datacontexts of datagrid row are different so you can apply the template like this:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentControl Content="{Binding User}" 
                            ContentTemplate="{StaticResource NameCellTemplate}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top