Hello. I'm unable to get a simple rotation animation to work properly on a simple WPF application. I'm targeting .NET 8. Here's what I've done:
Created a new WPF C# application using VS2022 Community. My MainWindow.xaml looks like the following:
<Window x:Class="Test1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Button x:Name="testButton" Content="Test" Click="Button_Click"/>
</Window>
When I click on the button, I'd like it to rotate back and forth between 0 and 180 degrees, animated over 250ms. The code-behind file is as follows:
public partial class MainWindow : Window
{
RotateTransform testButtonRotateTransform;
public MainWindow()
{
InitializeComponent();
TransformGroup transformGroup = new TransformGroup();
ScaleTransform scaleTransform = new ScaleTransform(0.8, 0.8);
testButtonRotateTransform = new RotateTransform(0);
transformGroup.Children.Add(scaleTransform);
transformGroup.Children.Add(testButtonRotateTransform);
testButton.RenderTransformOrigin = new Point(0.5, 0.5);
testButton.RenderTransform = transformGroup;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(testButtonRotateTransform.Angle == 0)
{
DoubleAnimation angleRotationAnimation = new DoubleAnimation(
0,
180,
new Duration(TimeSpan.FromMicroseconds(250)));
testButtonRotateTransform.BeginAnimation(
RotateTransform.AngleProperty,
angleRotationAnimation);
}
else
{
DoubleAnimation angleRotationAnimation = new DoubleAnimation(
180,
0,
new Duration(TimeSpan.FromMicroseconds(250)));
testButtonRotateTransform.BeginAnimation(
RotateTransform.AngleProperty,
angleRotationAnimation);
}
}
}
When I build and run this simple applicaiton, clicking the button does indeed cause it to rotate. However, the rotation is instantaneous i.e. there is no animation. What is going wrong here? Thanks in advance!