A Programmer's Dream

WPF-Fading Background

Posted by Stephen Wrighton on 30 Dec 2008

Well, the project I'm working on has a few pretties in it; and it has a few tabs that will appear based upon click events on other tabs. Typically, these magically appearing tabs are generated in the primary working area of the application, yet in one scenario, the appearing tab needed to be in the secondary data (for lack of a better term) area of the application.

Since, this is effectively non-standard behavior from the application, I wanted to provide a nice visual cue on this happening. I wanted the background to appear one color, and then slowly fade to its standard color.

That would be a nice, visual cue about this new window opening. So, I went forth and tried to do it. My first attempt involved using a brush, and then just changing the opacity until it was transparent. That was utter fail. So, realizing that I wasn't as clever as I had hoped, I turned to my old friend Google.

Where I discovered a bit about Storyboards and ColorAnimation objects. Now, I'm not overtly familiar with WPF, and in fact there's quite a bit that I just don't know yet about it; but I was shocked at how easily this worked.

What I did was created 2 new SolidColorBrushes, one for the FROM color and one for the TO color. These two colors would be the beginning and ending state for the background of my control. I then shoved these into my ResourceDictionary so that a) I could easily find and manipulate them and b) utilize them elsewhere if needed.

Next, I went to the user control I was working with and created on it three new objects, a storyboard, and then two local brush objects.

Then in the method I had for loading the control and its data, I created a ColorAnimation object, cloned my two new brushes into my local brush objects, and then shoved them all together. I activated a timer, and when the timer expired, then I turned on the animation to begin the fade.

Lo, and behold, it worked! And it worked well. It's pretty, it works great as an indicator, all-in-all I was quite pleased with myself.

Anyways, the following two screencaps show the relevant code in question.



Enjoy.

Tweet me @kidananubix if you like this post.

Tweet