I wanted to add simple fade out/fade in animations to my page transitions in my Silverlight 3 app. I decided to tackle the fade in animation first, and my first attempt was to add a FadeIn storyboard to the LayoutRoot Grid of each of my pages like so:
<Grid.Triggers>
<EventTrigger RoutedEvent="Grid.Loaded">
<BeginStoryboard>
<Storyboard x:Name="FadeIn">
<DoubleAnimation Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="Opacity"
From="0" To="1" Duration="0:0:0.300"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
You also have to add an Opacity of 0 to your LayoutRoot Grid. There are 2 issues with this approach. 1. You can't work in the designer anymore, as it's now set to invisible. 2. There is now duplicate xaml in every page, if you want to make changes to your animations than you'll have to do it in every single page.
My second attempt was to try and fade in/fade out the frame within MainPage.xaml. I set the frame's opacity to 0. The cool thing is that you can add storyboards to be invoked by code rather than attaching them to individual controls:
<UserControl.Resources>
<Storyboard x:Name="FadeIn">
<DoubleAnimation Storyboard.TargetName="Frame" Storyboard.TargetProperty="Opacity"
From="0" To="1" Duration="0:0:0.200"/>
</Storyboard>
<Storyboard x:Name="FadeOut">
<DoubleAnimation Storyboard.TargetName="Frame" Storyboard.TargetProperty="Opacity"
From="1" To="0" Duration="0:0:0.200"/>
</Storyboard>
</UserControl.Resources>
Next I had some work to do in the code-behind:
private Button lnkMenu = null;
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
this.FadeOut.Completed += new EventHandler(FadeOut_Completed);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
FadeIn.Begin();
}
private void NavButton_Click(object sender, RoutedEventArgs e)
{
lnkMenu = sender as Button;
FadeOut.Begin();
}
void FadeOut_Completed(object sender, EventArgs e)
{
String page = lnkMenu.Tag.ToString();
this.Frame.Navigate(new Uri(page, UriKind.Relative));
FadeIn.Begin();
}
Now we have all the page transition animation code in one place so we don't have to deal with the maintainability issue of having it in each page. Also the designers for every single page (including MainPage.xaml) will work now that we're not setting the opacity of any of the pages to 0.
7382fead-b187-4ec7-b3e2-bd991b6326aa|3|5.0