WPF ellipse rotate in mvvm DoubleAnimation,RotateTransform.AngleProperty press enter run and others pause,then press enter resume from paused angle

//xaml
<Window x:Class="WpfApp26.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp26"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <behavior:Interaction.Triggers>
        <behavior:EventTrigger EventName="KeyDown">
            <behavior:InvokeCommandAction Command="{Binding KeyDownCommand}" 
                                          PassEventArgsToCommand="True"/>
        </behavior:EventTrigger>
    </behavior:Interaction.Triggers>
    <Grid>
        <Ellipse x:Name="elp"                 
                 Width="{Binding ElpHeight,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 Height="{Binding ElpHeight,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 StrokeThickness="50"
                 RenderTransformOrigin="0.5,0.5">            
            <Ellipse.Fill>
                <ImageBrush ImageSource="{Binding ImgBrush}"/>
            </Ellipse.Fill>
            <Ellipse.RenderTransform>
                <RotateTransform x:Name="rotateTransform"/>
            </Ellipse.RenderTransform>
            <Ellipse.Stroke>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                    <GradientStop Color="Red" Offset="0"/>
                    <GradientStop Color="Orange" Offset="0.2"/>
                    <GradientStop Color="Yellow" Offset="0.4"/>
                    <GradientStop Color="Green" Offset="0.6"/>
                    <GradientStop Color="Blue" Offset="0.8"/>
                    <GradientStop Color="Cyan" Offset="1.0"/>
                </LinearGradientBrush>
            </Ellipse.Stroke>
        </Ellipse>
    </Grid>
</Window>

//cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfApp26
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM(this);
            this.DataContext = vm;
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        private Window win;
        private FrameworkElement fe;
        private Ellipse elp;
        private RotateTransform rotateTransform;
        private bool isRunning = true;
        private DoubleAnimation rotateAnimation;
        public MainVM(Window winValue)
        {
            win= winValue;
            if (win!=null)
            {
                win.Loaded+=Win_Loaded;
            }
        }

        private void Win_Loaded(object sender, RoutedEventArgs e)
        {
            var tempFE = win.Content as FrameworkElement;
            if (tempFE!=null)
            {
                fe= tempFE;
                ElpHeight = fe.ActualHeight;
            }

            var tempElp = win.FindName("elp") as Ellipse;
            if (tempElp!=null)
            {
                elp=tempElp;
            }

            var tempRotater = win.FindName("rotateTransform") as RotateTransform;
            if (tempRotater!=null)
            {
                ImgBrush=GetImageSourceViaUrl(@"../../../Images/10.jpg");
                rotateTransform= tempRotater;
                rotateAnimation = new DoubleAnimation();
                rotateAnimation.Duration=TimeSpan.FromSeconds(3);
                rotateAnimation.From=rotateTransform.Angle;
                rotateAnimation.To=rotateTransform.Angle+360;
                rotateAnimation.RepeatBehavior=RepeatBehavior.Forever;
                //elp.BeginAnimation(tempRotater.Angle, animation);
                ToggleRotation(true);
            }
        }

        private void ToggleRotation(bool shouldRun)
        {
            if (rotateTransform == null)
            {
                return;
            }

            if (shouldRun)
            {
                rotateAnimation.From=rotateTransform.Angle;
                rotateAnimation.To=rotateTransform.Angle+360;
                rotateAnimation.RepeatBehavior=RepeatBehavior.Forever;
                rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);
            }
            else
            {
                // Stop animation by applying the current angle as a fixed value
                double currentAngle = rotateTransform.Angle;
                rotateTransform.BeginAnimation(RotateTransform.AngleProperty, null);
                rotateTransform.Angle = currentAngle;
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = PropertyChanged;
            if (handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        private double elpHeight;
        public double ElpHeight
        {
            get
            {
                return elpHeight;
            }
            set
            {
                if (value != elpHeight)
                {
                    elpHeight=value;
                    OnPropertyChanged(nameof(ElpHeight));
                }
            }
        }

        private ImageSource imgBrush;
        public ImageSource ImgBrush
        {
            get
            {
                return imgBrush;
            }
            set
            {
                if (value!= imgBrush)
                {
                    imgBrush=value;
                    OnPropertyChanged(nameof(ImgBrush));
                }
            }
        }

        private ImageSource GetImageSourceViaUrl(string imgUrl)
        {
            BitmapImage bmi = new BitmapImage();
            if (File.Exists(imgUrl))
            {
                bmi.BeginInit();
                bmi.UriSource=new Uri(imgUrl, UriKind.RelativeOrAbsolute);
                bmi.EndInit();
                if (bmi.CanFreeze)
                {
                    bmi.Freeze();
                }
            }
            return bmi;
        }

        private DelCommand keyDownCommand;
        public DelCommand KeyDownCommand
        {
            get
            {
                if (keyDownCommand==null)
                {
                    keyDownCommand=new DelCommand(KeyDownCommandExecuted);
                }
                return keyDownCommand;
            }
        }

        private void KeyDownCommandExecuted(object? obj)
        {
            var e = obj as KeyEventArgs;
            if (e.Key==Key.Enter)
            {
                ToggleRotation(true);
            }
            else
            {
                ToggleRotation(false);
            }
        }
    }

    public class DelCommand : ICommand
    {
        private Action<object?> execute;
        private Predicate<object?> canExecute;
        public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue = null)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object? parameter)
        {
            return canExecute==null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            execute(parameter);
        }
    }
}

 

 

 

 

 

 

image

 

 

image

 

 

 

 

image

 

 

 

image

 

posted @ 2025-08-06 17:28  FredGrit  阅读(14)  评论(0)    收藏  举报