Silverlight's syntax and object model is quite similar to WPF. However, there are some important differences (at least in Beta 1; maybe these differences will disappear in RTM). Today I found another difference concerning the creation of animations in code.
Check out the following WPF code. It works without any problem (it fades in a yellow rectangle):
using System;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Create_And_Run_Animation();
}
public void Create_And_Run_Animation()
{
var storyBoard = new Storyboard();
var animation = new DoubleAnimation();
Storyboard.SetTargetName(animation, "Rect");
Storyboard.SetTargetProperty(animation, new PropertyPath(Rectangle.OpacityProperty));
animation.To = 1;
animation.Duration = TimeSpan.FromSeconds(5);
storyBoard.Children.Add(animation);
Resources.Add(storyBoard,"sb");
storyBoard.Begin(this);
}
}
}
Note that I call Create_And_Run_Animation in the window's constructor.
If you try the same thing in Silverlight 2.0 Beta 1 it does not work. The rectangle does not fade in:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace SilverlightApplication1
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
Create_And_Run_Animation();
}
public void Create_And_Run_Animation()
{
var storyBoard = new Storyboard();
var animation = new DoubleAnimation();
Storyboard.SetTargetName(animation, "Rect");
Storyboard.SetTargetProperty(animation, "Opacity");
animation.To = 1;
animation.Duration = TimeSpan.FromSeconds(5);
storyBoard.Children.Add(animation);
Resources.Add(storyBoard);
storyBoard.Begin();
}
}
}
However, if you move the call to Create_And_Run_Animation into the handler of the loaded-event everthing works fine:
using [...];
namespace SilverlightApplication1
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
LayoutRoot.Loaded += new RoutedEventHandler(LayoutRoot_Loaded);
}
void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
Create_And_Run_Animation();
}
public void Create_And_Run_Animation()
{
[...]
}
}
}
I hope this tip will save you some time!