Franckentien
Franckentien

Reputation: 324

Call EventTrigger RoutedEvent in Class MainWindow.xaml.cs

I have an EventTrigger called when a TextBlock is loaded:

<TextBlock Name="Hit" Text="Hit!">
 <TextBlock.Triggers>
  <EventTrigger RoutedEvent="TextBlock.Loaded">
   <BeginStoryboard>
    <Storyboard>
       <DoubleAnimation 
       Storyboard.TargetProperty="Opacity"
       From="0" To="1" Duration="0:0:1"/>
    </Storyboard>
   </BeginStoryboard>
  </EventTrigger>
 </TextBlock.Triggers>
</TextBlock>

But I want to create my own launcher and call this EventTrigger directly in my C# class.
Can someone help me?

Upvotes: 0

Views: 502

Answers (1)

Justin CI
Justin CI

Reputation: 2741

My understanding is that you need to call the story board when text box loads.

Below code worked for me.

Xaml:

<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:WpfApplication6"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>

            <Storyboard x:Key="animation">
                <DoubleAnimation 
       Storyboard.TargetProperty="Opacity"
       From="0" To="1" Duration="0:0:1"/>
            </Storyboard>

    </Window.Resources>

    <Window.DataContext>
        <vm:ViewModel></vm:ViewModel>
    </Window.DataContext>
    <Grid x:Name="grid">
        <StackPanel>
        <TextBlock Name="Hit" Width="200" Height="100" Text="Hit!">          
        </TextBlock>       
        </StackPanel>       
    </Grid>
</Window>

Code:

public MainWindow()
        {
            this.InitializeComponent();
            Hit.Loaded += Hit_Loaded;

        }

        private void Hit_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sb = this.FindResource("animation") as Storyboard;
            Storyboard.SetTarget(sb, this.Hit);
            sb.Begin();
        }

Upvotes: 1

Related Questions