代码之家  ›  专栏  ›  技术社区  ›  Rob

对多种类型重复使用数据模板?

  •  0
  • Rob  · 技术社区  · 11 年前

    我有以下内容 DataTemplate 用于显示 User 实例:

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

    我目前使用它来自定义模板列,如下所示:

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

    此列属于一个包含 使用者 实例,但我想在不同的数据网格中为列重用数据模板。第二个数据网格绑定到一个不同的类型,该类型保持 使用者 作为一处房产,所以我会 喜欢 要做到这一点:

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

    然而 Binding 属性不允许用于模板列。

    如何为列模板指定绑定路径,或修改数据模板,以便数据模板可以用于任一数据网格?

    1 回复  |  直到 11 年前
        1
  •  2
  •   Rob    11 年前

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

    <DataGridTemplateColumn>
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ContentControl Content="{Binding User}" 
                                ContentTemplate="{StaticResource NameCellTemplate}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>