【发布时间】:2016-05-26 20:22:34
【问题描述】:
为了了解动画和 UI,我正在制作一个基本的 WPF/C# 应用程序,其中用户选择要显示的车辆数量,然后这些车辆(即不同车辆的图像)出现在画布中并四处移动。
WPF 非常简单:
<Grid>
<Canvas x:Name="MenuTabCanvas" Visibility="Visible">
<Label x:Name="AnimateDemo" Content="Animate!" HorizontalAlignment="Left" VerticalAlignment="Top" Width="104" Background="#25A0DA" Foreground="White" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Cursor="Hand" MouseDown="AnimateGrid" Canvas.Left="640" Canvas.Top="87"/>
<Canvas x:Name="AnimationCanvas" Canvas.Top="150" Canvas.Left="224" Width="814" Height="489">
</Canvas>
</Grid>
我开始使用this post 中描述的方法制作淡入淡出动画,效果很好。然后我尝试了如下所示的 translatetransform,将淡入淡出代码留在 cmets 中,图像出现但没有任何移动:
private void AnimateGrid(object sender, EventArgs e)
{
int NumberOfVehicles = 5;
var sb = new Storyboard();
for (int i = 0; i < NumberOfVehicles; i++)
{
//create & add the images to our target canvas
Image Img = getRandomVehicleImage(); //returns image of vehicle
AnimationCanvas.Children.Add(Img);
Canvas.SetTop(Img, 30 + 60 * i); //position image w/in canvas
Canvas.SetLeft(Img, 30 + 80 * i);
//add an animation
DoubleAnimation myAnimation = new DoubleAnimation()
{
// From = 0,
To = 150,
Duration = TimeSpan.FromSeconds(2),
};
Storyboard.SetTarget(myAnimation, Img);
// Storyboard.SetTargetProperty(myAnimation, new PropertyPath(Button.OpacityProperty));
Storyboard.SetTargetProperty(myAnimation, new PropertyPath(TranslateTransform.XProperty));
sb.Children.Add(myAnimation);
}
sb.Begin();
}
我已经能够让它与 TranslateTransform.BeginAnimation 一起使用,但我更愿意在此处使用情节提要。
为什么平移变换的行为与不透明动画不同,我需要做什么才能使其按预期运行?
【问题讨论】: