Hello Everyone! This is Tushar.
Today, I am going to tell you how to implement Fade-In and Fade-Out effects for windows in WPF.
Edit Code in Visual Studio |
- Create a new project or open an existing project. Right click on Project in solution explorer and select Add New Item... Now a window is shown to you. Select Window and give appropriate name to your window (e.g. MyWindow.xaml) and click on OK.
- Create a transparent window as I have described in my previous blog Transparent Window [WPF].
- Create a Close button as I have described in previous blog.
- OK. Now we’ll handle behavior of window from Code behind. There will be two situations:
I. Window will Fade-In when window get loaded.
II. Window will Fade-Out when window get unloaded. - Now right click on your window in solution explorer and select Edit in Visual Studio. As soon as you do this, Expression Blend communicates with Visual Studio and your project gets loaded into visual studio.
- Now Open Code-Behind file for your window (in our case MyWindow.xaml.cs) and you can see a class there. Now Set Opacity property of the window to 0(zero) in the constructor of the class.
- To Fade-In window at the start-up, follow the following steps I. Create a Window Loaded event handler for the window to be faded. To do this, go back to Blend and select Window from Object and Timeline Panel and go to Properties panel and click on Events icon. Here you can see many events related to window. Double click on Loaded event TextBox. Now again Visual studio gets loaded automatically and you can see an EventHandler method is generated there in the Code-Behind file. II. Inside Event Handler method, write the following code snippet
var ObjAnimation = new DoubleAnimation(1,(Duration)TimeSpan.FromSeconds(0.5));this.BeginAnimation(UIElement.OpacityProperty, ObjAnimation); - To Fade-Out window at the start-up, follow the following steps:
I. Inside Event Handler method for close button, write the following code snippetvar ObjAnimation = new DoubleAnimation(0,(Duration)TimeSpan.FromSeconds(0.5));ObjAnimation.Completed += new EventHandler(Animation_FadeOutCompleted);this.BeginAnimation(UIElement.OpacityProperty, ObjAnimation); - As the animation completes, an event handler method named Animation_FadeOutCompleted is invoked. The Event-Handler is added for this method at line No. 3 in the code snippet. We close the window as soon as fade-out animation completes. The event handler method is written as :
void Animation_FadeOutCompleted(object sender, EventArgs e){this.Close();}
- That's it! Now go back to Blend and select your solution and right click and select Test Solution.
Happy Coding :)
No comments:
Post a Comment