Tuesday, February 10, 2009

WPF Animations

WARNING: This blog post assumes you have some software development experience in WPF and/or Sliverlight. If you don't, then go here.


The title of my blog says "the ramblings and words of a computer crazed individual", but I don't think I've actually written anything computer related on here. Well, there's a first to everything!

For the last couple of months, I've been working in WPF. I've had yet another sharp learning curve to tackle in my attempts at producing the next generation of Public Safety Software. One of the hardest concepts for me to grasp was what to do about Height animations. Take this scenario:

You've got a Panel that you want to remove, and the way you want to do it is by making it shrink, then setting it's Visibility to Collapsed. But the catch is that the panel that you want to animate is a variable height (Auto). WPF will complain about animating a Height (or Width) attribute that is set to Auto. It will actually throw an exception. This is because Auto really means Double.NaN. There are two ways around this: a code hack, or the preferred method.

In the code hack, you catch a routed event, measure the panel, and fire the animation with a now known value. This also causes a layout render for the parent control as well as your animated one.

The better method simply involves modifying the ScaleTransform value from 1 (full height) to 0, which is collapsed. Then you set the Visibility of the Panel to Collapsed. (or vice versa on making it appear). I don't have a code sample on me, but the ScaleTransform can all be done in XAML.

Another way around this is to avoid the height animation and simply change the Panel/Control/Whatever Visibility to Visible while keeping the opacity at 0, then fading it in. It's really up to you on how you want to have it done.

I'll try to update this with a code sample, but don't hold your breath.

2 comments:

Jared said...

Wow. As a semi-intelligent person who has attended (if not yet completed) college and actually worked with computers a decent amount, and worked for IBM, I still understood perhaps 1 word in 3. I am humbled.

Adhis said...

What?