我正在尝试制作一个简单的应用程序,在其中我在屏幕上反弹图像并旋转它。我希望旋转速度是动态的,并且每当图像碰到包含窗口的一侧时都会发生变化。所以,我试图弄清楚如何动态地改变旋转速度甚至方向。我正在尝试传入速度值并使用动画动态更改旋转。
无论如何,我正在尝试通过为 AngleProperty 设置动画并绑定到 XAML 中的 Angle 来测试动态更改旋转的能力。我一定做错了什么,因为图像不会旋转。
对此的任何帮助将不胜感激!
谢谢,柯蒂斯
这是我的 XAML:
<UserControl x:Class="Scooter.Bug"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Loaded="Bug_OnLoaded"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Image x:Name="_image" Source="Images/Author.png" RenderTransformOrigin="0.5, 0.5">
<Image.RenderTransform>
<RotateTransform Angle="{Binding Angle}"/>
</Image.RenderTransform>
</Image>
</Grid>
</UserControl>
这是我的代码隐藏:
using System;
using System.Windows;
using System.Windows.Media.Animation;
namespace Scooter
{
public partial class Bug
{
public static readonly DependencyProperty SpinSpeedProperty = DependencyProperty.Register("SpinSpeed", typeof (TimeSpan), typeof (Bug), new PropertyMetadata(default(TimeSpan)));
public static readonly DependencyProperty AngleProperty = DependencyProperty.Register("Angle", typeof (double), typeof (Bug), new PropertyMetadata(default(double)));
public Bug()
{
InitializeComponent();
}
void _timer_Tick(object sender, EventArgs e)
{
Angle = Angle >= 360 ? 0 : Angle + 1;
}
public TimeSpan SpinSpeed
{
get { return (TimeSpan) GetValue(SpinSpeedProperty); }
set { SetValue(SpinSpeedProperty, value); }
}
public double Angle
{
get { return (double) GetValue(AngleProperty); }
set { SetValue(AngleProperty, value); }
}
private void Bug_OnLoaded(object sender, RoutedEventArgs e)
{
DoubleAnimation animation = new DoubleAnimation
{
From = 0,
To = 360,
RepeatBehavior = RepeatBehavior.Forever,
Duration = SpinSpeed
};
_image.BeginAnimation(AngleProperty, animation);
}
}
}