Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » XAML » Your first animations using XAML and Silverlight - Color animation: Part I

Your first animations using XAML and Silverlight - Color animation: Part I

In this article, I will give a trick of how to deal with ColorAnimation class within VS2008 and Silverlight context using both xaml and C# 4.0, afterward, and in the two subsequent articles, we’ll focus on the DoubleAnimation and PointAnimation.

Author Rank:
Technologies: .NET 2.0, Database, Silverlight, XAML,Visual C# .NET
Total downloads :
Total page views :  4362
Rating :
 5/5
This article has been rated :  1 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor



Visual Studio 2008 and .Net framework 3.5 provide us several new features not found in the precedent version. The WPF, the XAML and Silverlight are among the new features introduced in a WPF context. They contribute to the amelioration of the application ergonomic side by introducing something new like 2D/3D animations. For instance, Visual studio 2008 and Silverlight products must be installed before starting with animations. For me, this is my first experience within VS 2008, XAML, WPF and Silverlight.  

As you will see, a given animation can target a given control such as a rectangle, a grid or an even a button witches are called canvas. The animation by definition is this context is the given control property or properties changement from given statue to another via an interpolation that could be monitored by the developer via code xaml or via the page code behind. I mean C # code. It is similar phenomenon when comparing with the flash animations, if you have already dealt with flash projects especially the movement and the form interpolations. There are three main animations in addition to a set of witches those provided by the System.Window.Media.Animation namespace,  all could be used in order to achieve a particular goal, but in this article and the ones witches will follow this one,  we'll concentrate on the three kind of animations, namely the Double animation, the Color animation and the point animation, moreover, the .Net frameworks provides a set of base classes such DoubleAnimationBase, ColorAnimationBase and PointAnimationBase to customize your code in addition to other classes like Aniamtable and interfaces such as IAnimatable. All of them are provided to perform customized animations within your WPF application.

In this article, I will give a trick of how to deal with ColorAnimation class within VS2008 and Silverlight context using both xaml and C# 4.0, afterward, and in the two subsequent articles, we'll focus on the DoubleAnimation and PointAnimation:

The Color animation:

In this example we will define a rectangle that changes color from yellow to red if the mouse enters the given object boundaries and then returns to the first color if the mouse leaves the rectangle.

XAML code:

Create a new WPF application by open New>Project>WPFApplication then name your application my first WPF application. Copy and paste this under code to the xaml zone.

<Window x:Class="myWpfApplication.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1" Height="400" Width="400" Loaded="Window_Loaded">

<!—The rectangle extends the Animatable class so it can be target of an

 Animation therefore a chose it -->

    <Rectangle Width="250" Height="250" ToolTip="This is myRectangle" Name="myRectangle" Visibility="Visible" Fill="Yellow">

        <Rectangle.Triggers>

             <!—The mouse enter event is the one that triggers the animation -->

 

            <EventTrigger RoutedEvent="Rectangle.MouseEnter">

            <!—The Storyboard is a sort of aniamtion container-->

 

                <BeginStoryboard>

                    <Storyboard>

                    <!—The color, the duration, and the targeted property that will

                       Be subject of the aniamtion, all parameters are set within the animation tag  -->

 

                        <ColorAnimation Storyboard.TargetName="myRectangle"

                                         Storyboard.TargetProperty="(Fill).(Color)"

                                         Duration="00:00:08"

                                         From="Yellow" To="Red"

                                       

                                         />

                    </Storyboard>

                </BeginStoryboard>

            </EventTrigger>

            <!—As you see, you can implement more that one animation for the same

               Object at the same time -->

          <EventTrigger RoutedEvent="Rectangle.MouseLeave">

                <BeginStoryboard>

                    <Storyboard>

                        <ColorAnimation Storyboard.TargetName="myRectangle" Storyboard.TargetProperty="(Fill).(Color)"

                                        Duration="00:00:08" From="Red" To="Yellow"

                                        />

                    </Storyboard>

                </BeginStoryboard>

            </EventTrigger>

        </Rectangle.Triggers>

    </Rectangle>

</Window>

C# code:

Also this task could be performed using the form code behind, I mean C#, to do so open a new window drag and drop a new rectangle.

Figure 1

Then right click on it and choose the properties menu.

Figure 2

Afterward, select the properties menu item and set it property name to "myRectangle" width to "250" and it height to "250".

Then implement the code as bellow, but don't forget to append System.Windows.Media.Animation namespace to the project:

//It is used to fill myRectangle object

SolidColorBrush TransformBrush;

//This animation is for changing the color

ColorAnimation oColorAnimation;

private void Window_Loaded(object sender, RoutedEventArgs e)

{

//First we set the color to yellow

TransformBrush = new SolidColorBrush(Colors.Yellow);

//Fill the rectangle using the TransformBrush

myRectangle.Fill = TransformBrush;

//Those two lines are responsibles for triggering events MouseEnter and MouseLeave

myRectangle.MouseEnter+=new MouseEventHandler(myRectangle_MouseEnter);

myRectangle.MouseLeave+=new MouseEventHandler(myRectangle_MouseLeave);

}

private void myRectangle_MouseEnter(object sender, RoutedEventArgs e)

{

//Set the animation

oColorAnimation = new ColorAnimation();

 

//The initial brush state

oColorAnimation.From = Colors.Yellow;

//The final brush state

oColorAnimation.To = Colors.Red;

//The animation duration

oColorAnimation.Duration = TimeSpan.FromSeconds(8);

//Trigger the animation

TransformBrush.BeginAnimation(SolidColorBrush.ColorProperty, oColorAnimation);

 

}

private void myRectangle_MouseLeave(object sender, RoutedEventArgs e)

{

//Set the animation

oColorAnimation = new ColorAnimation();

 

//The initial brush state

oColorAnimation.From = Colors.Red;

//The final brush state

oColorAnimation.To = Colors.Yellow;

//The animation duration

oColorAnimation.Duration = TimeSpan.FromSeconds(8);

//Trigger the animation

TransformBrush.BeginAnimation(SolidColorBrush.ColorProperty, oColorAnimation);

} 

As you remark, the code is not very complex, especially for someone who had already good experience with .Net environment. You should not miss the second part "Your first animation using XAML and Silverlight - double animation: Part II".

Good Dotneting!!! 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Bechir Bejaoui
The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
very goodvv12/18/2008
hi, its really good ,keep posting the articles :) regards, vinoth
Reply | Email | Delete | Modify | 
 
 
Re: very goodBechir12/19/2008

Hi,

I already posted a couple of articles about Silverlight and I think that they will be published soon so don't miss them and give your rate ;-)

Reply | Email | Delete | Modify | 
 
Re: Re: very goodvv12/19/2008

Hi,

please copy paste and run this code below and help me in doing the animation in popup when you click on the listview items, the popup should expand very slowly when the mouse enter and collapse back when the mouse leave, expecting your reply :). i tried with the time duration found in the popup say some 5 secs, but it displaying only after 5 secs suddenly, i dont want the popup to display suddenlt, hope ui understand my problem, please rply soon ;-)

 

<Window x:Class="WpfApplication4.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="List_View Example" Height="301" Width="361" WindowStartupLocation="Manual"

xmlns:sys="clr-namespace:System;assembly=mscorlib" >

<Window.Resources>

<XmlDataProvider x:Key="employee_DS" Source="data.xml"

x:Name="empdata" />

<Style x:Key="{x:Type Button }" TargetType="{x:Type Button}">

<Setter Property="FontFamily" Value="Tahoma" />

<Setter Property="FontSize" Value="10" />

<Setter Property="Height" Value="65" />

<Setter Property="Margin" Value="20,20,20,0" />

</Style>

</Window.Resources>

<Window.Background>

<!-- background gradient -->

<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">

<LinearGradientBrush.GradientStops>

<GradientStop Color="Aqua" Offset="0" />

<GradientStop Color="BlanchedAlmond" Offset="0.5" />

<GradientStop Color="Chocolate" Offset="0.9" />

<GradientStop Color="DarkOrange" Offset="1" />

</LinearGradientBrush.GradientStops>

</LinearGradientBrush>

</Window.Background>

 

<StackPanel >

<Grid>

<ListView Name="lstvwEmployees" Margin="25,0,21,-156" ItemTemplate="{DynamicResource EmployeeTemplate}"

ItemsSource="{Binding Source={StaticResource employee_DS},

XPath=/wipro_employee/employee}" SelectionChanged="ListView_SelectionChanged" Cursor="Hand" MouseEnter ="lstvwEmployees_MouseEnter" Height="99" VerticalAlignment="Bottom">

<!-- for mouse enter event ,it triggers the scaletransform-->

<ListView.ItemContainerStyle>

<Style TargetType="ListViewItem">

<Style.Triggers>

<Trigger Property="IsMouseOver" Value="True">

<Setter Property="Panel.ZIndex" Value="{x:Static sys:Int32.MaxValue}"/>

<Setter Property="RenderTransform">

<Setter.Value>

<ScaleTransform ScaleX="1" ScaleY="1"/>

</Setter.Value>

</Setter>

<Trigger.EnterActions>

<BeginStoryboard>

<Storyboard>

<ParallelTimeline BeginTime="0:0:0">

<DoubleAnimation Duration="00:00:00.3000000" To="1.5" Storyboard.TargetProperty="RenderTransform.(ScaleTransform.ScaleY)"/>

<DoubleAnimation Duration="00:00:00.3000000" To="1.5" Storyboard.TargetProperty="RenderTransform.(ScaleTransform.ScaleX)"/>

</ParallelTimeline>

</Storyboard>

</BeginStoryboard>

</Trigger.EnterActions>

<Trigger.ExitActions>

<BeginStoryboard>

<Storyboard>

<ParallelTimeline BeginTime="0:0:0">

<DoubleAnimation Duration="00:00:00.3000000" To="2" Storyboard.TargetProperty="RenderTransform.(ScaleTransform.ScaleY)"/>

<DoubleAnimation Duration="00:00:00.3000000" To="2" Storyboard.TargetProperty="RenderTransform.(ScaleTransform.ScaleX)"/>

</ParallelTimeline>

</Storyboard>

</BeginStoryboard>

</Trigger.ExitActions>

</Trigger>

</Style.Triggers>

</Style>

</ListView.ItemContainerStyle>

<!-- for listview to show animation as outer glow effect-->

<ListView.BitmapEffect>

<BitmapEffectGroup>

<OuterGlowBitmapEffect GlowColor="CornflowerBlue" GlowSize="15"/>

<DropShadowBitmapEffect ShadowDepth="10" Softness="5"/>

<BevelBitmapEffect BevelWidth="15"/>