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 ones used for showing / hiding parts of the user interface.
With Silvelight, 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:
It's a pretty simple peice 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:
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 simple 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:
Here is a XAML snippet from the example:
Note the storyboard name is prefixed with the element name. And here is how this animation, and the legend's, is triggered from code:
You can download the full sourcecode for the example project: showHideAnimations.zip.
Regards,Colin E.