如何使用c#在wpf中动态旋转文本块?

时间:2016-06-14 06:06:31

标签: c# wpf

我这样想但是我没有得到轮换。我收到了以下错误:

  

无法将“System.Windows.Media.TransformGroup”类型的对象强制转换为   输入'System.Windows.Media.RotateTransform'。

TextBlock txt = new TextBlock();
txtb.Text="Sample";

var rotateAnimation = new DoubleAnimation(0, 270, TimeSpan.FromSeconds(5));

var rt = (RotateTransform)txt.RenderTransform;
rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);

2 个答案:

答案 0 :(得分:0)

如果我清楚地了解你想要的是为Textblock制作动画!

        TextBlock txt = new TextBlock();            
        txt.Text = "Sample";
        txt.HorizontalAlignment = HorizontalAlignment.Center;
        txt.VerticalAlignment = VerticalAlignment.Center;
        RotateTransform r1 = new RotateTransform();
        txt.RenderTransform = r1;
        MainGrid.Children.Add(txt);  //MainGrid is the name of your main layout

        var rotateAnimation = new DoubleAnimation(0, 270, TimeSpan.FromSeconds(5));
        rotateAnimation.RepeatBehavior = RepeatBehavior.Forever;
        var rt = (RotateTransform)txt.RenderTransform;
        rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);

答案 1 :(得分:0)

试试这个。您可以在RenderTransform上使用动画:

var rotateAnimation = new DoubleAnimation(0, 270, TimeSpan.FromSeconds(5));
var rt = (RotateTransform) textblock2.RenderTransform;
rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);

在您的Xaml中,您可以添加RotateTransform:

<TextBlock>
  <TextBlock.RenderTransform>
    <RotateTransform Angle="0"/>
  </TextBlock.RenderTransform>
</TextBlock>