Search code examples
c#wpfxaml

Expanding animation from center of grid


I am making an app where when it opens it expands. But it is expanding from the side of the grid but I want it to expand from the center. Here is the xaml code

    <Window.Resources>
        <Storyboard x:Key="ExpandingAnimation">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="ExpandingGrid" Storyboard.TargetProperty="(FrameworkElement.Height)">
                <EasingDoubleKeyFrame KeyTime="00:00:00" Value="0"></EasingDoubleKeyFrame>
                <EasingDoubleKeyFrame KeyTime="00:00:01" Value="0"></EasingDoubleKeyFrame>
                <EasingDoubleKeyFrame KeyTime="00:00:03" Value="222"></EasingDoubleKeyFrame>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </Window.Resources>

<Grid x:Name="ExpandingGrid"> </Grid>

And this is the c# code

        public MainWindow()
        {
            InitializeComponent();
            Storyboard ExpandingAnime = (Storyboard)TryFindResource("ExpandingAnimation");
            ExpandingAnime.Begin();
        }

Here is an example of how it looks like.


Solution

  • You could use a ScaleTransform and animate its ScaleX and ScaleY properties:

    <Storyboard x:Key="ExpandingAnimation">
        <Storyboard>
            <DoubleAnimation
                Storyboard.TargetName="MyScaleTransform"
                Storyboard.TargetProperty="(ScaleTransform.ScaleX)"
                From="0" To ="1" Duration="0:0:3"/>
            <DoubleAnimation
                Storyboard.TargetName="MyScaleTransform"
                Storyboard.TargetProperty="(ScaleTransform.ScaleY)"
                From="0" To ="1" Duration="0:0:3"/>
        </Storyboard>
    </Storyboard>
    ...
    <Grid x:Name="ExpandingGrid"
                  RenderTransformOrigin="0.5,0.5"
                  Height="222">
        <Grid.RenderTransform>
            <ScaleTransform x:Name="MyScaleTransform" ScaleX="0" ScaleY ="0" />
        </Grid.RenderTransform>
    </Grid>