How to add StringFormat to a text block inside a DataTemplate?

I have the following DataTemplate:

<DataTemplate x:Key="ColoringLabels">
    <TextBlock Padding="0"
               Margin="0"
               Name="Username"
               Text="{Binding Username}"
               Foreground="Gray"
               FontStyle="Italic"
              />
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding IsLoggedIn}" Value="True">
            <Setter TargetName="Username" Property="FontSize" Value="14"/>
            <Setter TargetName="Username" Property="Foreground" Value="Green"/>
            <Setter TargetName="Username" Property="FontStyle" Value="Normal"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

I would like to use the template in ListView, where each username is followed by a; and space.

The template effect will then behave as it was written:

<DataTemplate x:Key="ColoringLabels">
    <TextBlock Padding="0"
               Margin="0"
               Name="Username"
               Text="{Binding Username, StringFormat='{}{0}; '}"
               Foreground="Gray"
               FontStyle="Italic"
              />
    <DataTemplate.Triggers>
      ...
    </DataTemplate.Triggers>
</DataTemplate>

How can I extend the original template to get the result of the second?

+5
source share
1 answer

There is no direct mechanism for one DataTemplate to inherit the properties of another.

However, you can successfully avoid code duplication with styles that have inheritance capabilities.

I believe this will give you what you need:

    <Style x:Key="StandardBoundTb" TargetType="TextBlock">
        <Setter Property="Padding" Value="0" />
        <Setter Property="Margin" Value="0" />
        <Setter Property="Text" Value="{Binding Path=Username}" />
        <!-- etc -->
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsLoggedIn}" Value="True">
                <Setter Property="FontSize" Value="14" />
                <!-- etc -->
            </DataTrigger>
        </Style.Triggers>
    </Style>
    <Style x:Key="DelimitedBoundTb" TargetType="TextBlock" 
           BasedOn="{StaticResource StandardBoundTb}"
    >
        <Setter Property="Text" Value="{Binding Path=Username, StringFormat='{}{0}; '}" />
    </Style>

    <DataTemplate x:Key="ColoringLabels">
        <TextBlock Style="{StaticResource StandardBoundTb}" />
    </DataTemplate>
    <DataTemplate x:Key="ColoringLabelsDelimited">
        <TextBlock Style="{StaticResource DelimitedBoundTb}" />
    </DataTemplate>
+6
source

All Articles