by gleblanc
9. January 2009 19:29
In Part II of this serie dedicated to master pages in Silverlight, we will improve the previous program by adding an animation that is executed at page switching time.
Project / source code
First, we are dynamically adding an animation to each content page (here
Page1 and
Page2) :
public Page()
{
InitializeComponent();
page1 = new Page1();
page2 = new Page2();
PageContainer.Children.Add(page1);
// animation for Page1 (Scale animation on X)
ScaleTransform scaleTrans = new ScaleTransform();
scaleTrans.SetValue(NameProperty, "scale");
page1.RenderTransform = scaleTrans;
page1.RenderTransformOrigin = new Point(0.5, 0.5);
Storyboard stb = new Storyboard();
stb.Duration = new Duration(TimeSpan.FromSeconds(1));
DoubleAnimation daX = new DoubleAnimation {From=0.1, To=1 };
Storyboard.SetTargetName(daX, "scale");
Storyboard.SetTargetProperty(daX, new PropertyPath("ScaleX"));
stb.Children.Add(daX);
page1.Resources.Add("AnimPage", stb);
// animation for Page2 (Scale animation on Y)
scaleTrans = new ScaleTransform();
scaleTrans.SetValue(NameProperty, "scale");
page2.RenderTransform = scaleTrans;
page2.RenderTransformOrigin = new Point(0.5, 0.5);
stb = new Storyboard();
stb.Duration = new Duration(TimeSpan.FromSeconds(1));
DoubleAnimation daY = new DoubleAnimation {From=0.1, To=1 };
Storyboard.SetTargetName(daY, "scale");
Storyboard.SetTargetProperty(daY, new PropertyPath("ScaleY"));
stb.Children.Add(daY);
page2.Resources.Add("AnimPage", stb);
}
Each Storyboard for animation is named
AnimPage and is added as resource in the page. An animation takes some time, here one second. To disable page switching while an animation is active, we declare a boolean :
bool bRunningAnim;
Our SwitchToPage function becomes :
public void SwitchToPage(UserControl p)
{
if (bRunningAnim) return; // animation in progress
Page masterPage = Application.Current.RootVisual as Page;
UserControl currentPage = masterPage.PageContainer.Children[0] as UserControl;
if (currentPage != p)
{
masterPage.PageContainer.Children.Add(p);
Storyboard stb = p.Resources["AnimPage"] as Storyboard;
stb.Completed += new EventHandler(stb_Completed);
stb.Begin();
bRunningAnim = true;
}
}
The new page is first added to the children of the content area grid cell (PageContainer, see previous post). Two pages are now displayed (more precisely, the second one will soon be displayed). We retrieve the
AnimPage animation and launch it.
In the Completed function, we remove the old page from the content area and mark the animation as terminated :
void stb_Completed(object sender, EventArgs e)
{
if (!bRunningAnim) return;
Page masterPage = Application.Current.RootVisual as Page;
masterPage.PageContainer.Children.RemoveAt(0);
bRunningAnim = false;
}
See you soon for a next improvement.