Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a StringFormat to a Textblock 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 a ListView where every username is followed by a ; and a space.

Effectively the template would then behave as it were written like this:

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

like image 552
Dabblernl Avatar asked Oct 25 '09 09:10

Dabblernl


1 Answers

There isn't a direct mechanism to have one DataTemplate inherit the properties of another one.

However, you can succesfully avoid code duplication by using styles, which DO have inheritance capabilities.

I believe this would 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>
like image 169
Andrew Shepherd Avatar answered Oct 23 '22 04:10

Andrew Shepherd