WPF/XAML Animate motion between grid cells

Viewed 32

In WPF/XAML I have an object (any - image, rectangle) positioned in grid with square cells. My command buttons can move the object between grid cells (by sliding or turning, depending on command type) but now I need to make the motion fluent (animated).

A demo of preferred result is at https://codepen.io/jenik/pen/vYdxmLL (in HTML/CSS/JS environment this is just a few simple lines of code).

I need to make same behaviour in WPF and I am absolutely lost in how to (I am missing handy relative coordinates like transform-origin: bottom left or translateX(-100%). Now I am only with plain "skipping" code:

<Window x:Class="WpfGridAnimation.MainWindow"
        <!-- ...omitted for brevity ... -->
        Title="MainWindow" Height="550" Width="800">
    <Window.Resources>
        <Style TargetType="Rectangle">
            <Setter Property="Fill" Value="Aquamarine"/>
            <Setter Property="Stroke" Value="LightGray"/>
        </Style>
    </Window.Resources>
    <StackPanel Orientation="Vertical">
        <Grid Width="400" 
              Height="400" 
              VerticalAlignment="Center" 
              HorizontalAlignment="Center">
            
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />                
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>                
            </Grid.RowDefinitions>
            
            <Rectangle x:Name="MyRectangle"
                       Grid.Column="3"
                       Grid.Row="2"/>
        </Grid>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
            <Button x:Name="ResetBtn" Content="Reset" Click="ResetBtn_Click"/>
            <Button x:Name="StartSlideBtn" Content="Start slide" Click="StartSlideBtn_Click"/>
            <Button x:Name="StartTurnBtn" Content="Start turn" Click="StartTurnBtn_Click"/>
        </StackPanel>
    </StackPanel>
</Window>

And C# (for brevity the handlers only)

private void ResetBtn_Click(object sender, RoutedEventArgs e)
{
    Grid.SetColumn(MyRectangle, 3);
    Grid.SetRow(MyRectangle, 2);
}

private void StartSlideBtn_Click(object sender, RoutedEventArgs e)
{
    Grid.SetColumn(MyRectangle, 4);
    Grid.SetRow(MyRectangle, 2);
    //How to prepare and start animation here?
}

private void StartTurnBtn_Click(object sender, RoutedEventArgs e)
{
    Grid.SetColumn(MyRectangle, 3);
    Grid.SetRow(MyRectangle, 3);
    //How to prepare and start animation here?
}
0 Answers
Related