Animating Page Elements When the Page Orientation Changes
The VisualStateManager
can be used to animate UIElements
when the page orientation changes. This can be done by defining a set of VisualStateGroups
corresponding to the PageOrientation
values.
Each VisualStateGroup
contains a collection of VisualState
objects, each containing a collection of Storyboard
objects that specify how an element’s properties change when the control is placed in a particular visual state.
In Listing 3, you see how the LandscapeRight VisualState
includes a set of DoubleAnimations
, which move various TextBlocks
on the page to new positions when the page orientation changes.
LISTING 3. OrientationView.xaml (excerpt)
<Grid x:Name="LayoutRoot">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="OrientationStates">
<!--Portrait up is the default state-->
<VisualState x:Name="PortraitUp">
<Storyboard />
</VisualState>
<VisualState x:Name="LandscapeRight">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="topLeft"
Storyboard.TargetProperty="
(UIElement.RenderTransform).(TranslateTransform.X)"
To="650" />
<!-- Content omitted. -->
</Storyboard>
</VisualState>
<!-- Content omitted. -->
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<!-- Content omitted. -->
<Grid x:Name="ContentGrid" Grid.Row="1">
<TextBlock Text="Top-left corner" x:Name="topLeft"
HorizontalAlignment="Left" VerticalAlignment="Top">
<TextBlock.RenderTransform>
<TranslateTransform/>
</TextBlock.RenderTransform>
</TextBlock>
<!-- Content omitted. -->
</Grid>
</Grid>
We subscribe to OrientationChanged
event within the view’s constructor, as shown in the following excerpt:
OrientationChanged += (sender, args) => VisualStateManager.GoToState(
this, args.Orientation.ToString(), true);
When the OrientationChanged
event is raised, the VisualStateManager
is directed to the state identified by the Orientation
property of the OrientationChangedEventArgs
(see Figure 3).
FIGURE 3 TextBlocks
are animated into position when page orientation changes.