Expand/Collapse Animation with UWP

In my latest app I wanted to have an UI element that could expand and collapse on demand – it was taking up a lot of screen real estate and I wanted to give the user a choice of whether to minimise part of it. Hooking a button up to change the visibility of the block is straight forward enough, but I’d like to have a nice animation to go with it – perhaps with the UI element below sliding upwards to expand into the new space. This is what I wanted to achieve:

First I found a stackoverflow answer that did most of what I wanted – but the bottom block didn’t slide upwards. This is because the CompositeTransform.ScaleY property scales the control but does not change the boundaries – I found this out in this post on MSDN. The key information is here:

Scaling transforms affect how the UIElement is rendered but don’t change other properties such as Height: the Height will remain whatever it is, but the overall image’s display size is stretched or shrunk (in this case shrunk) by the ScaleY factor.

So, if we want to change the height of the shrinking block, we need to change the height, and this is where I found out about Dependent and Independent animations.

A dependent animation is one that will cause the Xaml to re-layout. Expensive; therefore requiring an “opt-in”.

https://stackoverflow.com/questions/10479903/how-to-animate-height-of-control-in-windows-8-xaml

So, putting this together in a Storyboard, I had the following XAML code:

        <Storyboard x:Name="TestShrink">
            <!--  this works but only if From is also set.  -->
            <DoubleAnimation
                EnableDependentAnimation="True"
                Storyboard.TargetName="info"
                Storyboard.TargetProperty="Height"
                From="100"
                To="0"
                Duration="0:0:1" />
        </Storyboard>

I ran this and nothing happened. Then I added a “From” property and it shrank just fine. This is in contrast to the notes in the Microsoft documentation:

To only: The animation progresses from the animated property’s base value or a previous animation’s output value to the value specified by the To property.

https://docs.microsoft.com/en-us/uwp/api/Windows.UI.Xaml.Media.Animation.DoubleAnimation?view=winrt-20348

Clearly, the animation was not using the animated property’s base value as the starting value.

So, there was only one thing for it – to write this thing in code and retrieve/assign the height of the control programmatically. This, in C++/CX is what I ended up with as proof of concept code, and it should be reasonably easy to convert into C# or C++/WinRT if needed:

	// Configuration parameters.
	double animation_length_seconds = 5.0;
	FrameworkElement^ chevron = fiToggleShowConfig;
	FrameworkElement^ target = info;
	static double _openHeight = 0.0;

	// Create the storyboard.
	auto storyboard = ref new Windows::UI::Xaml::Media::Animation::Storyboard();

	double start_height = 0.0, end_height = 0.0;
	double start_opacity = 0.0, end_opacity = 0.0;
	double start_rotation = 0.0, end_rotation = 0.0;
	if (target->Visibility == Windows::UI::Xaml::Visibility::Visible) {
		_openHeight = target->ActualHeight;
		start_height = target->ActualHeight;
		end_height = 0.0;

		start_opacity = 1.0;
		end_opacity = 0.0;

		start_rotation = 0.0;
		end_rotation = 180.0;

		// Make the target collapsed at the end of the storyboard.
		{
			auto visible = ref new ObjectAnimationUsingKeyFrames();
			auto kf_start = ref new DiscreteObjectKeyFrame();
			KeyTime kt_start;
			TimeSpan ts_start;
			ts_start.Duration = 0;
			kt_start.TimeSpan = ts_start;
			kf_start->KeyTime = kt_start;
			kf_start->Value = Windows::UI::Xaml::Visibility::Visible;
			visible->KeyFrames->Append(kf_start);

			auto kf_end = ref new DiscreteObjectKeyFrame();
			KeyTime kt_end;
			TimeSpan ts_end;
			ts_end.Duration = (animation_length_seconds * 1000) * 1000;
			kt_end.TimeSpan = ts_end;
			kf_end->KeyTime = kt_end;
			kf_end->Value = Windows::UI::Xaml::Visibility::Collapsed;
			visible->KeyFrames->Append(kf_end);

			storyboard->SetTarget(visible, target);
			storyboard->SetTargetProperty(visible, "(UIElement.Visibility)");
			storyboard->Children->Append(visible);
		}

	} else {
		start_height = 0.0;
		end_height = _openHeight;

		start_opacity = 0.0;
		end_opacity = 1.0;

		start_rotation = 180.0;
		end_rotation = 0.0;

		// Make the target visible straight away.
		target->Visibility = Windows::UI::Xaml::Visibility::Visible;
	}

	// Shrinking the info size.
	{
		auto shrink = ref new DoubleAnimation();
		shrink->From = start_height;
		shrink->To = end_height;

		TimeSpan ts = TimeSpan();
		ts.Duration = (long long) ((animation_length_seconds * 1000) * 1000);
		shrink->Duration = ts;
		shrink->EnableDependentAnimation = true;

		storyboard->SetTargetProperty(shrink, "Height");
		storyboard->SetTarget(shrink, target);
		storyboard->Children->Append(shrink);
	}

	// Reducing the Opactity of the info.
	{
		auto hide = ref new DoubleAnimationUsingKeyFrames();
		auto start = ref new EasingDoubleKeyFrame();
		KeyTime kt;
		TimeSpan start_ts;
		start_ts.Duration = 0;
		kt.TimeSpan = start_ts;
		start->KeyTime = kt;
		start->Value = start_opacity;
		hide->KeyFrames->Append(start);

		auto end = ref new EasingDoubleKeyFrame();
		TimeSpan end_ts;
		end_ts.Duration = (animation_length_seconds * 1000) * 1000;
		KeyTime end_kt;
		end_kt.TimeSpan = end_ts;
		end->KeyTime = end_kt;
		end->Value = end_opacity;
		hide->KeyFrames->Append(end);
		
		storyboard->SetTarget(hide, target);
		storyboard->SetTargetProperty(hide, "(UIElement.Opacity)");
		storyboard->Children->Append(hide);
	}

	// Rotating the Chevron
	if (chevron != nullptr)
	{
		auto rotate = ref new DoubleAnimationUsingKeyFrames();

		auto kf_start = ref new EasingDoubleKeyFrame();
		KeyTime kt_start;
		TimeSpan ts_start;
		ts_start.Duration = 0;
		kt_start.TimeSpan = ts_start;
		kf_start->KeyTime = kt_start;
		kf_start->Value = start_rotation;
		rotate->KeyFrames->Append(kf_start);

		auto kf_end = ref new EasingDoubleKeyFrame();
		KeyTime kt_end;
		TimeSpan ts_end;
		ts_end.Duration = (animation_length_seconds * 1000) * 750;
		kt_end.TimeSpan = ts_end;
		kf_end->KeyTime = kt_end;
		kf_end->Value = end_rotation;
		rotate->KeyFrames->Append(kf_end);

		storyboard->SetTarget(rotate, chevron);
		storyboard->SetTargetProperty(rotate, "(UIElement.RenderTransform).(RotateTransform.Angle)");
		storyboard->Children->Append(rotate);
	}

	storyboard->Begin();

This can be easily compressed into a function for your needs, apologies that the naming scheme for variables isn’t consistent – this is very much proof of concept code written with kids running around !

This is the XAML that I have on the page:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <TextBlock
            Grid.ColumnSpan="2"
            Margin="10"
            FontSize="18"
            FontWeight="Bold">
            Text Header
        </TextBlock>

        <Grid x:Name="infogrid" Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="40" />
                <ColumnDefinition Width="500" />
            </Grid.ColumnDefinitions>

            <FontIcon
                x:Name="fiToggleShowConfig"
                Margin="10,10"
                HorizontalAlignment="Left"
                VerticalAlignment="Top"
                FontFamily="Segoe MDL2 Assets"
                Glyph="&#xE70D;"
                RenderTransformOrigin="0.5,0.5"
                Tapped="fiToggleShowConfig_Tapped">
                <FontIcon.RenderTransform>
                    <RotateTransform />
                </FontIcon.RenderTransform>
            </FontIcon>

            <TextBlock
                x:Name="info"
                Grid.Column="1"
                Margin="10"
                TextWrapping="Wrap">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                <TextBlock.RenderTransform>
                    <CompositeTransform />
                </TextBlock.RenderTransform>
            </TextBlock>

        </Grid>

        <TextBlock
            Grid.Row="2"
            Grid.ColumnSpan="2"
            Margin="10"
            FontSize="18"
            FontWeight="Bold">
            Another Title
        </TextBlock>

        <TextBlock
            Grid.Row="3"
            Grid.ColumnSpan="2"
            Margin="10"
            TextWrapping="Wrap">
            Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
        </TextBlock>
</Grid>

The code is run when the fiToggleShowConfig control is tapped, and as the animation is dependent and running on the UI thread, nothing more can happen with the UI until it is complete – therefore you don’t have to handle a new animation being started before the current one is complete.

It does mean that everything else you need to run on the UI thread will be delayed until it is complete though.