WPF绑定到RotateTransform.Angle不起作用

时间:2013-09-05 22:39:09

标签: c# wpf xaml rotatetransform rendertransform

我正在尝试制作一个简单的应用,在屏幕上反射图像并旋转它。我希望旋转速度是动态的,并且只要图像碰到包含窗口的一侧,就会改变。所以,我试图找出如何动态改变旋转的速度,甚至可能是方向。我正在尝试传递一个速度值并用动画动态地改变旋转。

无论如何,我试图通过设置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);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您在图片上调用BeginAnimation(),但使用AngleProperty中的Bug

您可以在BeginAnimation()

上使用RotateTransform
_image.RenderTransform.BeginAnimation(RotateTransform.AngleProperty, animation);

或在您的控件上致电BeginAnimation()

this.BeginAnimation(AngleProperty, animation);