在故事板上有一个 SpeedRatio 设置,它是持续时间的乘数。但是,您不能绑定到它,因为它不是依赖属性。
要解决这个问题,您可以使用情节提要上的 SetSpeedRatio 函数。请注意,这仅在故事板以代码启动时才有效(否则您会收到错误)。
下面的代码是如何在对象中引发事件以影响旋转矩形动画速度的完整示例。文本框和数据绑定的目的是更新背景对象。该按钮只是使文本框失去焦点并更新对象。
<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="300" Width="300">
<StackPanel>
<Rectangle Margin="50" Width="50" Height="50" Fill="Red" x:Name="rc">
<Rectangle.RenderTransform>
<RotateTransform x:Name="TransRotate"
CenterX="25" CenterY="25" Angle="0" />
</Rectangle.RenderTransform>
<Rectangle.Resources>
<Storyboard x:Key="spin">
<DoubleAnimation x:Name="da"
Storyboard.TargetName="TransRotate"
Storyboard.TargetProperty="Angle"
By="360"
Duration="0:0:10"
AutoReverse="False"
RepeatBehavior="Forever" />
</Storyboard>
</Rectangle.Resources>
</Rectangle>
<TextBox Text="{Binding Speed}" />
<Button>Update Speed</Button>
</StackPanel>
</Window>
然后是C#代码
{
public Window1()
{
InitializeComponent();
//create new object
BackgroundObject bo = new BackgroundObject();
//binding only needed for the text box to change speed value
this.DataContext = bo;
//Hook up event
bo.SpeedChanged += bo_SpeedChanged;
//Needed to prevent an error
Storyboard sb = (Storyboard)rc.FindResource("spin");
sb.Begin();
}
//Change Speed
public void bo_SpeedChanged( object sender, int newSpeed)
{
Storyboard sb = (Storyboard)rc.FindResource("spin");
sb.SetSpeedRatio(newSpeed);
}
}
public delegate void SpeedChangedEventHandler(object sender, int newSpeed);
public class BackgroundObject
{
public BackgroundObject()
{
_speed = 10;
}
public event SpeedChangedEventHandler SpeedChanged;
private int _speed;
public int Speed
{
get { return _speed; }
set { _speed = value; SpeedChanged(this,value); }
}
}
我相信你可以适应你的使用。