Blue Theme Orange Theme Green Theme Red Theme
 
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 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:
Total page views :  6632
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
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
 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.
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.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
very good by vv On December 18, 2008
hi, its really good ,keep posting the articles :) regards, vinoth
Reply | Email | Delete | Modify | 
Re: very good by Bechir On December 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 good by vv On December 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"/>

</BitmapEffectGroup>

</ListView.BitmapEffect>

<ListView.View>

<GridView >

<GridViewColumn Header="Code" Width="50" DisplayMemberBinding="{Binding XPath=Code}" />

<GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding XPath=Name}"/>

<GridViewColumn Header="Country" DisplayMemberBinding="{Binding XPath=Country}"/>

</GridView>

</ListView.View>

</ListView>

<Button Height="34" Name="button1" Width="77" HorizontalAlignment="Right" Margin="0,0,21,-201" VerticalAlignment="Bottom" Click="button1_Click">Close Window</Button>

</Grid>

<!-- button to show animation as outer glow effect-->

 

<Popup Placement="Mouse" Name="popup" PopupAnimation="Slide"

DataContext="{StaticResource employee_DS}" AllowsTransparency="True">

 

 

<Grid Name="grid1" Background="Gray" DataContext="{Binding}">

<TextBlock Margin="20,27,10,22" >Details of the Employee</TextBlock>

<Label Margin="20,48,172,0" Content="Code" Height="24" VerticalAlignment="Top"></Label>

<Label Content="Name" Margin="20,86,0,132" HorizontalAlignment="Left" Width="43"></Label>

<Label Content="Country" Margin="20,124,0,106" HorizontalAlignment="Left" Width=" 50"></Label>

<Button Background="ForestGreen" Margin="0,0,10,0" Name="ex" Content="Exit" Click="Button_Click_1" HorizontalAlignment="Right" Width="69" Height="26" VerticalAlignment="Bottom"></Button>

<TextBox Text="{Binding XPath=Code}" Height="26" Margin="108,54,32,0" Name="textBox1" VerticalAlignment="Top"/>

<TextBox Text="{Binding XPath=Name}" Height="26" Margin="108,89,32,0" Name="textBox2" VerticalAlignment="Top"/>

<TextBox Text="{Binding XPath=Country}" Height="27" Margin="107,124,32,0" Name="textBox3" VerticalAlignment="Top"/>

<Label HorizontalAlignment="Left" Margin="20,158,0,142" Name="Label1" Width="83">Age</Label>

<TextBox Text="{Binding XPath=age}" Margin="107,164,32,139" Name="textBox4" />

<Label Height="32" HorizontalAlignment="Left" Margin="21,0,0,90" Name="label2" VerticalAlignment="Bottom" Width="94">Job Status</Label>

<TextBox Text="{Binding XPath=job}" Height="25" Margin="107,0,30,95" Name="textBox5" VerticalAlignment="Bottom" />

<Label Height="32" HorizontalAlignment="Left" Margin="21,0,0,30" Name="label3" VerticalAlignment="Bottom" Width="83">Details</Label>

<Label Content="{Binding XPath=details}" Height="63" Margin="93,0,18,22" Name="label4" VerticalAlignment="Bottom"></Label>

</Grid>

</Popup>

<Grid>

<Grid.Triggers>

<!-- story board for mouse enter animation-->

<EventTrigger RoutedEvent='Rectangle.MouseEnter' Storyboard.TargetName="popup" Storyboard.TargetProperty="(Popup.IsOpen)">

<EventTrigger.Actions>

<BeginStoryboard>

<Storyboard>

<DoubleAnimation

Storyboard.TargetName="lstvwEmployees"

Storyboard.TargetProperty="Opacity"

To="1.0" Duration="0:0:1"/>

</Storyboard>

</BeginStoryboard>

</EventTrigger.Actions>

</EventTrigger>

<EventTrigger RoutedEvent='Rectangle.MouseLeave'>

<EventTrigger.Actions>

<BeginStoryboard>

<Storyboard>

<DoubleAnimation

Storyboard.TargetName="lstvwEmployees"

Storyboard.TargetProperty="Opacity"

To="0.3" Duration="0:0:2"/>

</Storyboard>

</BeginStoryboard>

</EventTrigger.Actions>

</EventTrigger>

</Grid.Triggers>

</Grid>

</StackPanel>

</Window>

Reply | Email | Delete | Modify | 
Re: Re: Re: very good by Bechir On December 19, 2008

Ok,

I will run it and see what we can do 

Reply | Email | Delete | Modify | 
Re: Re: Re: Re: very good by vv On December 19, 2008

thanks a lot , you can find the animation what i am mentioning in my question in th MSDN home page in top right corner. When u move mouse over the Microsoft.com , you can see the popup like something come and going back on mouse enter and mouse leave event.

thanks,

regards

vinoth :)

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.