Windows 8 Dev Tip: Animating Attached Properties

posted on 18 Jul 2012 | .NET | Windows Store Apps | XAML

When you're working with Metro Style apps, eventually you'll want to animate an attached property. A common example is changing which grid row or column an element is in when reacting to a layout change.

Let's give it a try:

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="ApplicationViewStates">
        <VisualState x:Name="FullScreenLandscape" />
        <VisualState x:Name="Filled" />
        <VisualState x:Name="FullScreenPortrait" />
        <VisualState x:Name="Snapped">
            <Storyboard>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="gridItem"
                                               Storyboard.TargetProperty="Grid.Column">
                    <DiscreteObjectKeyFrame KeyTime="0"
                                            Value="0" />
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

Oops! That didn't work:

Error

So what's the secret sauce for Attached Properties? Parentheses.

So let's try again:

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="ApplicationViewStates">
        <VisualState x:Name="FullScreenLandscape" />
        <VisualState x:Name="Filled" />
        <VisualState x:Name="FullScreenPortrait" />
        <VisualState x:Name="Snapped">
            <Storyboard>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="gridItem"
                                               Storyboard.TargetProperty="(Grid.Column)">
                    <DiscreteObjectKeyFrame KeyTime="0"
                                            Value="0" />
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

No more errors!