Search code examples
c#xamlwindows-8visualstatemanager

Switching between static-width and Auto-width with Visual States


I'm having a minor issue with my current app, dealing with visual states and automatic / static widths.

Depending on the visual state, a StackPanel either has a width="Auto" or width="400". Blend is telling me I can't animate between these two values (and I'm not really animating here, but simply switching between a fullscreen video and a composite view). Now I have to do an explicit test and change the width when I change my Visual State (through the VisualStateManager-framework. Is there any way I can do this in XAML (through the storyboards) instead of in the codebehind?

Some code samples of what I'm doing today:

private void Trailer_OnFullScreenToggled(object sender, EventArgs e)
{
    var state = (Trailer.IsFullScreen() ? "Windowed" : "Fullscreen");

    // HACK: Done to get past the auto / px issue
    VisualsGrid.Width = Trailer.IsFullScreen() ? 400.0 : Double.NaN;

    VisualStateManager.GoToState(this, state, true);
}

Any help would be greatly appreciated!


Solution

  • The "Auto" value for width is aliased to Double.NaN. This is why the animation fails -- it can't do interpolation to or from that value.

    Have you tried using a keyframe animation with a discrete keyframe? Using a discrete keyframe animation should get around the problem that the animation system can't interpolate to or from Double.NaN since no interpolation will happen.

    I'm not in front of a development environment at the moment, so I'm not sure if you would need to use a DoubleAnimationUsingKeyFrames with a DiscreteDoubleKeyFrame and a value of Double.NaN or a StringAnimationUsingKeyFrames with a DiscreteStringKeyFrame and a value of Auto.

    That, of course, will not do a smooth animation from a fixed width to auto-sizing but instead will pop between the two.