Search code examples
c#wpfanimationstoryboard

WPF storyboard as a resource


I'm trying to fade in then fade out a label and it seems to work from some parts of my code but not from others..

So, for the xaml I have :

<Page x:Class=""Gtec2.MindBeagle.ChoosePatient"   .. .bla bla bla>
    <Page.Resources>
        <Resources Dictionary>
            <Storyboard x:Key="fadeInStory" Storyboard.TargetName="noPatientsLabel" Storyboard.TargetProperty="Opacity">
                <DoubleAnimation From="1" To="0" Duration="0:0:0.300"/>
            </Storyboard>
            <!-- Other resources as imagesources, styles and stuff -->
        </Resources Dictionary>
     </Page.Resources>
     <Grid>
         <!-- A lot of things -->
         <!-- And the guy I want to fadeIn and Out-->
         <TextBlock Name="noPatientsLabel" TextAlignment="Center" VerticalAlignment="Center" Grid.Column="1" Grid.Row="1" IsHitTestVisible="False">
        No Patients found <LineBreak/>
        please check the filters
         </TextBlock>
         <!-- A lot of things -->
     </Grid>
</Page>

And for the Code behind (C#) I have Plenty of things and a method like this one:

public void FadeIn()
{
    Storyboard sb = FindResource("fadeInStory") as Storyboard;
    sb.Begin();
}

IT seems to work from the very same cs file but when other operations are calling this method to make the label appear it complains saying "'noPatientsLabel' name cannot be found in the name scope of 'Gtec2.MindBeagle.ChoosePatient'."

Thoughts?


Solution

  • I finally created an static class called AnimationHelper with some useful functions. Here you have an example

    public static void FadeOut(UIElement target, int milliseconds)
        {
           DoubleAnimation da = new DoubleAnimation();
           da.From = target.Opacity;
           da.To = 0.0;
           da.Duration = TimeSpan.FromMilliseconds(milliseconds);
           da.AutoReverse = false;
    
           System.Windows.Media.Animation.Storyboard.SetTargetProperty(da, new PropertyPath("Opacity"));
           System.Windows.Media.Animation.Storyboard.SetTarget(da, target);
    
           System.Windows.Media.Animation.Storyboard sb = new System.Windows.Media.Animation.Storyboard();
           sb.Children.Add(da);
    
           sb.Begin();
       }
    

    same for fade in or whatever. You can also return the storyboard ( public static System.Windows.Media.Animation.Storyboard FadeIn (UIElement target) { ... }.

    If you do so, you can attach to the finished event :)

    Extremelly useful :)