Search code examples
wpfxamlstylestextblock

How can I convert this TextBlock fade-in trigger to a Style


This XAML makes text fade in when it appears.

I would like to put this functionality into a Style.

However, but what do I put in for the "TargetName" since the style doesn't know which element is going to be using it?

How can I convert this fade-in effect to a style?

<TextBlock Name="Message" Text="This is a test.">
  <TextBlock.Triggers>
    <EventTrigger RoutedEvent="TextBlock.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimation
            Storyboard.TargetName="Message" 
            Storyboard.TargetProperty="(TextBlock.Opacity)"
            From="0.0" To="1.0" Duration="0:0:3"/>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </TextBlock.Triggers>
</TextBlock>

Solution

  • You don't have to use TargetName. This works:

    <Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
      <Page.Resources>
        <Style TargetType="TextBlock">
          <Style.Triggers>
            <EventTrigger RoutedEvent="TextBlock.Loaded">
              <BeginStoryboard>
                <Storyboard>
                  <DoubleAnimation
                    Storyboard.TargetProperty="(TextBlock.Opacity)"
                    From="0.0" To="1.0" Duration="0:0:3"/>
                </Storyboard>
              </BeginStoryboard>
            </EventTrigger>
          </Style.Triggers>
        </Style>  
      </Page.Resources>
      <Grid>
        <TextBlock Name="Message" Text="This is a test.">
        </TextBlock>
      </Grid>
    </Page>