Infinitely rotate rectangle in XAML
Asked Answered
C

1

36

How to define XAML to rotate a rectangle infinitely?

So far I found a solution with code but no xaml: http://www.codeproject.com/Articles/23257/Beginner-s-WPF-Animation-Tutorial which I use like this:

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
    var doubleAnimation = new DoubleAnimation(360, 0, new Duration(TimeSpan.FromSeconds(1)));
    var rotateTransform = new RotateTransform();
    
    rect1.RenderTransform = rotateTransform;
    rect1.RenderTransformOrigin = new Point(0.5, 0.5);
    doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
    
    rotateTransform.BeginAnimation(RotateTransform.AngleProperty, doubleAnimation);
}

But how can I achieve this with XAML only?

Congressional answered 6/9, 2012 at 10:28 Comment(5)
galasoft.ch/mydotnet/articles/article-2006102701.aspx this explains both code-behind and XAML version.. google.com!Batey
It looks what I'm looking for, I'll check that. Thanks.Congressional
Your question's code was an answer to my question. Thanks!Gadolinium
Your most welcome :-DCongressional
Heh, needed the code, so thanks. As to why we ever use XAML given it is twice as long and somewhat obtuse I leave to philosophers.Lalapalooza
D
76

Something like this

<Rectangle x:Name="rect1" RenderTransformOrigin="0.5, 0.5">
  <Rectangle.RenderTransform>
    <!-- giving the transform a name tells the framework not to freeze it -->
    <RotateTransform x:Name="noFreeze" />
  </Rectangle.RenderTransform>
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimation
            Storyboard.TargetProperty="(Rectangle.RenderTransform).(RotateTransform.Angle)"
            To="-360" Duration="0:0:1" RepeatBehavior="Forever" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

Of course you can remove Loaded trigger and run this storyboard whenever you want.

Dromedary answered 6/9, 2012 at 10:43 Comment(4)
I needed to add CenterX="16" CenterY="16" to the RotateTransform to center the origin in my 32x32 rectangle.Belfry
FYI, if you're here because you've tried this and you're getting an error about animating a frozen property, that's because WPF is aggressively freezing elements in your tree now. To provide a hint to the framework not to freeze the transform, simply give your transform an x:Name, which the framework sees and assumes you'll be referencing it from code and so won't freeze it.Agential
For the noobs like me, this also needs a stroke, strokeThickness, background color, size etc. <Rectangle x:Name="rect1" RenderTransformOrigin="0.5, 0.5" Width="50" Height="50" Stroke="Black" StrokeThickness="10">Everick
@Belfry It's more practical to use RenderTransformOrigin=".5, .5" and prevent manual positioning as much as you can.Chessa

© 2022 - 2024 — McMap. All rights reserved.