XAML: What ever happened to the tag?
There has been a recent change in the Windows Presentation Foundation in regards to Storyboards (at least since the December 2005 CTP, possibly even earlier). Most of the articles you currently find on the internet and the few Avalon books suggest the following:
<Window x:Class="MinhNguyen.HelloWorld"
xmlns="https://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="https://schemas.microsoft.com/winfx/xaml/2005"
Title="HelloWorld"
Width="860" Height="570"
>
<Window.Storyboards>
<ParallelTimeline>
<DoubleAnimation ...></DoubleAnimation>
</ParallelTimeline>
</Window.Storyboards>
Turns out that the <Window.Storyboards> tag doesn't exist anymore. Of course, you can still hook up an animation to an event trigger like so:
<Button Grid.Column="0" Grid.Row="2">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<ParallelTimeline>
<DoubleAnimation ...></DoubleAnimation>
...
</ParallelTimeline>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
But what if your animation is not tied to a particular control or event and you want to start it from code-behind? I googled on this for a long while to no avail, but the answer was given to me on an internal mailing list and it is embarassingly simple. Simply define your storyboard as a resource, like so:
<Window x:Class="MinhNguyen.HelloWorld"
xmlns="https://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="https://schemas.microsoft.com/winfx/xaml/2005"
Title="HelloWorld"
Width="860" Height="570"
>
<Window.Resources>
<BeginStoryboard x:Key="myAnimation">
<Storyboard>
<ParallelTimeline>
<DoubleAnimation ...></DoubleAnimation>
...
</ParallelTimeline>
</Storyboard>
</BeginStoryboard>
</Window.Resources>
and then you can retrieve and start your animation from code behind like so:
void SomeMethod()
{
myAnimation = (BeginStoryboard)this.Resources["myAnimation"];
myAnimation.Storyboard.Begin(this);
}
In other words, what used to be defined in <Window.Storyboards> should now be treated as a resource. I thought I share this with you all so that you don't waste time wondering why Window.Storyboards is missing, when reading the outdated books (funny, huh? The September 2005 book Programming Windows Presentation Foundation that I am currently reading is already outdated).
Comments
- Anonymous
April 04, 2006
Hey thanks for the tip... same problem here (and same book)
Cheers! - Anonymous
April 10, 2006
In the codebehind you may want to use this.FindResource("myAnimation");