Home > Software design >  How do i rotate an image animated on button click in WPF through C# code (Not XAML)
How do i rotate an image animated on button click in WPF through C# code (Not XAML)

Time:06-10

I dont know if im approaching this wrong or if there is an error in my code.

And as i said above i would like to solve the problem through C# code and not in XAML.

I don't get any compiler errors it just does nothing.

XAML:

    <Button Content="Rotate" HorizontalAlignment="Left" Margin="1007,637,0,0" VerticalAlignment="Top" Click="Button_Click" Height="36" Width="51"/>
    <Image x:Name="Brett" Margin="0,-563,0,187" Stretch="Fill" Source="/Monopoly_Brett_bib.png" RenderTransformOrigin="0.5, 0.5" OpacityMask="White"></Image>

C#:

private void Button_Click(object sender, RoutedEventArgs e)
    {

        DoubleAnimation doubleAnimation = new DoubleAnimation();
        doubleAnimation.Duration = new Duration(new TimeSpan(0, 0, 0, 3, 0));
        Storyboard storyBoard = new Storyboard();
        storyBoard.Children.Add(doubleAnimation);
        Storyboard.SetTarget(doubleAnimation, Brett);
        Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(RotateTransform.AngleProperty));
        doubleAnimation.From = 0;
        doubleAnimation.To = -90;
        storyBoard.Begin();
        storyBoard.Completed  = StoryBoard_Completed;

    }

CodePudding user response:

Try this:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        DoubleAnimation doubleAnimation = new DoubleAnimation
        {
            From =0,
            To = -90,
            Duration = new Duration(TimeSpan.FromSeconds(3))
        };
        Storyboard storyBoard = new Storyboard();

        Brett.RenderTransform = new RotateTransform();

        storyBoard.Children.Add(doubleAnimation);
        Storyboard.SetTarget(doubleAnimation, Brett);
        Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("RenderTransform.Angle"));

        storyBoard.Begin();
    }
  • Related