我想使用故事板制作一个从旋转画布继承的组件。但是当我尝试没有任何事情发生时。
最终我还想动态地将旋转速度更改为停止。但首先,我需要旋转组件。
这是组件的代码:
class MyToy : Canvas
{
public MyToy()
{
this.Background = System.Windows.Media.Brushes.Green;
this.Width = 300;
this.Height = 300;
Polyline poly = new Polyline();
poly.Points.Add(new Point(25, 25));
poly.Points.Add(new Point(0, 50));
poly.Points.Add(new Point(25, 75));
poly.Points.Add(new Point(50, 50));
poly.Points.Add(new Point(25, 25));
poly.Points.Add(new Point(25, 0));
poly.Stroke = System.Windows.Media.Brushes.Blue;
poly.StrokeThickness = 10;
this.Children.Add(poly);
Canvas.SetLeft(poly, 120);
Canvas.SetTop(poly, 120);
}
}
窗口xaml代码是:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="500" Width="500">
<Canvas x:Name="myCanvas">
<Button Canvas.Left="0" Canvas.Top="0" Content="Rotate" Height="23" Name="button1" Width="111" Click="button1_Click" />
</Canvas>
</Window>
最后,我创建故事板的代码是:
public partial class Window1 : Window
{
MyToy myToy;
RotateTransform transform;
public Window1()
{
InitializeComponent();
myToy = new MyToy();
transform = new RotateTransform();
// transform.Name = "MyToy1Transform";
myToy.RenderTransform = transform;
// this.RegisterName(transform.Name, transform);
myToy.Name = "MyToy1";
this.RegisterName("MyToy1", myToy);
myCanvas.Children.Add(myToy);
Canvas.SetTop(myToy, 50);
Canvas.SetLeft(myToy, 50);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation ani = new DoubleAnimation();
ani.From = 0;
ani.To = 359;
ani.AutoReverse = true;
ani.RepeatBehavior = RepeatBehavior.Forever;
ani.Duration = new Duration(TimeSpan.FromSeconds(2));
Storyboard story = new Storyboard();
story.Children.Add(ani);
// Storyboard.SetTargetName(ani, myToy.Name);
Storyboard.SetTarget(ani, transform);
Storyboard.SetTargetProperty(ani, new PropertyPath(RotateTransform.AngleProperty));
story.Begin(this);
}
}
感谢您的帮助。
答案 0 :(得分:1)
动画的目标是MyToy对象,目标属性是Angle。虽然MyToy没有角度属性。解决方案:将MyToy的RenderTransform(或LayoutTransform)属性设置为新的RotateTransform对象。然后使用那个对象(具有Angle属性)作为动画的目标。