WPF 绑定到 RotateTransform.Angle 不起作用

本文关键字:Angle 不起作用 RotateTransform 绑定 WPF | 更新日期: 2023-09-27 18:30:17

我正在尝试制作一个简单的应用程序,我可以在屏幕上反弹图像并旋转它。 我希望旋转速度是动态的,每当图像到达包含窗口的一侧时都会发生变化。 所以,我试图弄清楚如何动态改变旋转的速度,甚至方向。 我正在尝试传入速度值并使用动画动态更改旋转。

无论如何,我只是尝试通过对 AngleProperty 进行动画处理并绑定到 XAML 中的角度来测试动态更改旋转的能力。 我一定做错了什么,因为图像不会旋转。

任何帮助将不胜感激!

谢谢柯蒂斯

这是我的 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);
        }
    }
}

WPF 绑定到 RotateTransform.Angle 不起作用

您正在对图像调用BeginAnimation(),但使用的是 Bug 中的AngleProperty

您可以在RotateTransform上使用BeginAnimation()

_image.RenderTransform.BeginAnimation(RotateTransform.AngleProperty, animation);

或调用控件上的BeginAnimation()

this.BeginAnimation(AngleProperty, animation);