Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#

Helpful Extension Methods for Show / Hide Animations in Silverlight

Rate me:
Please Sign up or sign in to vote.
4.83/5 (3 votes)
28 Sep 2009CPOL2 min read 17.1K   4   1
Today's blog post is a couple of very simple utility methods that I have found myself using again and again ...

Today’s blog post is a couple of very simple utility methods that I have found myself using again and again …

The animations that Silverlight developers have at their disposal are both varied and powerful. It is easy to get carried away and cover your application with gratuitous animations, which soon become an unwanted distraction. However, animation, when used sparingly, can make the user experience (much as I hate buzzwords, this one seems to have stuck!) smoother and more fluid. One class of animation which I think adds to program fluidity is the one used for showing / hiding parts of the user interface.

With Silverlight, the typical process for animation is to create a storyboard in XAML that animates the element being shown / hidden. This storyboard is looked-up in the resources and triggered at the right moment. The typical code looks something like this:

C#
Storyboard anim = layourRoot.Resources["myAnimation"] as Storyboard;
anim.Begin();

It’s a pretty simple piece of code, however, if you have multiple elements being shown / hidden, the management of resource names, and repeated code is a bit of a pain.

As an alternative, I have written a couple of very simple extension methods to FrameworkElement, as shown below:

C#
/// <summary>
/// Shows the element, playing a storyboard if one is present
/// </summary>
/// <param name="element"></param>
public static void Show(this FrameworkElement element)
{
    string animationName = element.Name + "ShowAnim";
 
    // check for presence of a show animation
    Storyboard showAnim = element.Resources[animationName] as Storyboard;
    if (showAnim != null)
    {
        showAnim.Begin();
    }
    else
    {
        element.Visibility = Visibility.Visible;
    }
}
 
/// <summary>
/// Hides the element, playing a storyboard if one is present
/// </summary>
/// <param name="element"></param>
public static void Hide(this FrameworkElement element)
{
    string animationName = element.Name + "HideAnim";
 
    // check for presence of a hide animation
    Storyboard showAnim = element.Resources[animationName] as Storyboard;
    if (showAnim != null)
    {
        showAnim.Begin();
    }
    else
    {
        element.Visibility = Visibility.Collapsed;
    }
}

What each of these extension methods does is check for the presence of a Storyboard named "ShowAnim" or "HideAnim", prefixed with the element name in order to ensure uniqueness. If the storyboard is present, the animation is played. Otherwise, the element visibility is set directly. This is a very useful feature, in that the Show() and Hide() extension methods can be used if you want to change an elements visibility without animation. If, at a later date, you then decide that you want this change in visibility to be animated, you simply add a storyboard to the XAML, without having to change the code.

Here is a simple example based on a previous blog post of mine:

42680/chart.png

NOTE: Codeproject does not support Silverlight content. See the above in action on the original blog post.

Here is an XAML snippet from the example:

XML
...
<Grid Name="Crosshair" Opacity="0">
    <Grid.Resources>
        <Storyboard x:Name="CrosshairShowAnim">
            <DoubleAnimation Storyboard.TargetName="Crosshair" 
                        Storyboard.TargetProperty="(UIElement.Opacity)"
                        To="1"  Duration="00:00:00.1"/>
        </Storyboard>
        <Storyboard x:Name="CrosshairHideAnim">
            <DoubleAnimation Storyboard.TargetName="Crosshair"                        
                        Storyboard.TargetProperty="(UIElement.Opacity)"
                        Duration="00:00:00.1" To="0"/>
        </Storyboard>
    </Grid.Resources>
    <Line Name="Vertical" X1="{Binding Path=X}" Y1="0"
          X2="{Binding Path=X}" Y2="400" Stroke="Black"/>
    <Line Name="Horizontal" X1="0" Y1="{Binding Path=Y}"
          X2="400" Y2="{Binding Path=Y}" Stroke="Black"/>
</Grid>
...

Note the storyboard name is prefixed with the element name. And here is how this animation, and the legend’s, is triggered from code:

C#
private void CrosshairContainer_MouseEnter(object sender, MouseEventArgs e)
{
    LocationIndicator.Show();
    Crosshair.Show();
    ChartRoot.Cursor = Cursors.None;
}
 
private void CrosshairContainer_MouseLeave(object sender, MouseEventArgs e)
{
    LocationIndicator.Hide();
    Crosshair.Hide();
    ChartRoot.Cursor = Cursors.Arrow;
}

You can download the full source code for the example project: showHideAnimations.zip.

Regards,
Colin E.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Scott Logic
United Kingdom United Kingdom
I am CTO at ShinobiControls, a team of iOS developers who are carefully crafting iOS charts, grids and controls for making your applications awesome.

I am a Technical Architect for Visiblox which have developed the world's fastest WPF / Silverlight and WP7 charts.

I am also a Technical Evangelist at Scott Logic, a provider of bespoke financial software and consultancy for the retail and investment banking, stockbroking, asset management and hedge fund communities.

Visit my blog - Colin Eberhardt's Adventures in .NET.

Follow me on Twitter - @ColinEberhardt

-

Comments and Discussions

 
GeneralMy vote of 5 Pin
maq_rohit29-Sep-10 21:45
professionalmaq_rohit29-Sep-10 21:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.