白小白之路C# 2024-01-01 23:19 采纳率: 50%
浏览 11

WPF触发器通过自定义属性控制界面关键帧动画的启停

关于WPF触发器控制关键帧动画,想通过一个自定义属性的值变化控制关键帧动画的启停。
自定义属性AnimateStart

 public class AnimateDP : DependencyObject
 {
     public bool AnimateStart
     {
         get { return (bool)GetValue(AnimateStartProperty); }
         set { SetValue(AnimateStartProperty, value); }
     }

     public static readonly DependencyProperty AnimateStartProperty =
                    DependencyProperty.Register("AnimateStart", typeof(bool), typeof(AnimateDP), new PropertyMetadata(true));
 }

自定义属性在viewmodel里通过按钮控制值的变化;

using CommunityToolkitMVVM.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace CommunityToolkitMVVM.ViewModels
{
    public class MainViewModel : ObservableObject
    {
        public Model calculateModel { get; set; }=new Model() {  A=0, B=0, C=0, IsStart=false};
        public AnimateDP AnimateDP { get; set; } = new AnimateDP() { AnimateStart = false };
        public MainViewModel()
        {          
            MyButtonCommand = new RelayCommand(() => AnimateDP.AnimateStart = true) ;
        }
        private RelayCommand myButtonCommand;

        public RelayCommand MyButtonCommand
        {
            get { return myButtonCommand; }
            set { myButtonCommand = value; }
        }
    }
}

界面是一个关键帧动画的Boder

 <Style x:Key="BorderColor" TargetType="Border" >
     <Style.Triggers>
         <DataTrigger Binding="{Binding AnimateDP.AnimateStart}" Value="True">
             <DataTrigger.EnterActions>
                 <BeginStoryboard >
                     <Storyboard RepeatBehavior="Forever" AutoReverse="True" >
                         <ColorAnimationUsingKeyFrames  Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
                             <EasingColorKeyFrame KeyTime="00:00:01" Value="#FFD22F2F"/>
                             <EasingColorKeyFrame KeyTime="00:00:02" Value="#FF70D12C"/>
                             <EasingColorKeyFrame KeyTime="00:00:03" Value="#FF2FD2D2"/>
                             <EasingColorKeyFrame KeyTime="00:00:04" Value="#FFC92CD1"/>
                             <EasingColorKeyFrame KeyTime="00:00:05" Value="#FFE8ED95"/>
                             <EasingColorKeyFrame KeyTime="00:00:06" Value="#FFE3BBE5"/>
                         </ColorAnimationUsingKeyFrames>
                     </Storyboard>
                 </BeginStoryboard>
             </DataTrigger.EnterActions>
         </DataTrigger>
     </Style.Triggers>
 </Style>

大概如图所示:

img


  • 写回答

2条回答 默认 最新

  • 白小白之路C# 2024-01-01 23:55
    关注

    知识点:WPF、触发器、样式、动画、MVVM

    界面
    <Window x:Class="CommunityToolkitMVVM.Views.MainView"
            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:local="clr-namespace:CommunityToolkitMVVM" xmlns:viewmodels="clr-namespace:CommunityToolkitMVVM.ViewModels" d:DataContext="{d:DesignInstance Type=viewmodels:MainViewModel}"
            mc:Ignorable="d"
            FontSize="20"
            Title="MainView" Height="450" Width="789">
        <Window.Resources>
            <Storyboard x:Key="Storyboard1" AutoReverse="True" RepeatBehavior="Forever">
                <ColorAnimationUsingKeyFrames Storyboard.TargetName="textBlock" Storyboard.TargetProperty="(TextBlock.Background).(SolidColorBrush.Color)">
                    <EasingColorKeyFrame KeyTime="00:00:01" Value="#FFD22F2F"/>
                    <EasingColorKeyFrame KeyTime="00:00:02" Value="#FF70D12C"/>
                    <EasingColorKeyFrame KeyTime="00:00:03" Value="#FF2FD2D2"/>
                    <EasingColorKeyFrame KeyTime="00:00:04" Value="#FFC92CD1"/>
                    <EasingColorKeyFrame KeyTime="00:00:05" Value="#FFE8ED95"/>
                    <EasingColorKeyFrame KeyTime="00:00:06" Value="#FFE3BBE5"/>
                </ColorAnimationUsingKeyFrames>
            </Storyboard>
            <Style x:Key="BorderColor" TargetType="Border" >
                <Style.Triggers>
                    <DataTrigger Binding="{Binding AnimateDP.AnimateStart}" Value="True">
                        <DataTrigger.EnterActions>
                            <BeginStoryboard >
                                <Storyboard RepeatBehavior="Forever" AutoReverse="True" >
                                    <ColorAnimationUsingKeyFrames  Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
                                        <EasingColorKeyFrame KeyTime="00:00:01" Value="Red"/>
                                        <EasingColorKeyFrame KeyTime="00:00:02" Value="Green"/>
                                        <EasingColorKeyFrame KeyTime="00:00:03" Value="Blue"/>
    
                                    </ColorAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </DataTrigger.EnterActions>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
        <Window.Triggers>
            <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                <BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
            </EventTrigger>
        </Window.Triggers>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="260"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <StackPanel Height="200" VerticalAlignment="Top"  HorizontalAlignment="Stretch" Grid.Row="0">
                <TextBox x:Name="textBox"   Text="{Binding calculateModel.A,UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TextBoxStyle1}"/>
                <TextBlock x:Name="textBlock"  Text="b"   Style="{StaticResource TextBlockStyle1}"/>
                <TextBox Text="{Binding calculateModel.B,UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TextBoxStyle1}"/>
                <TextBlock x:Name="textBlock1" Text="c" Style="{StaticResource TextBlockStyle1}"/>
                <TextBox Text="{Binding calculateModel.C,UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TextBoxStyle1}" />
                <Button Content="计算" Command="{Binding MyButtonCommand}" Height="30" Width="206" />
            </StackPanel>
            <StackPanel  Grid.Row="1">
                <Border   Background="Black" BorderThickness="3" BorderBrush="Black" Margin="156,10,504,-51" Style="{StaticResource BorderColor}" Height="100" Width="100">
                </Border>
            </StackPanel>
        </Grid>
    </Window>
    
    资源:
    <ResourceDictionary 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" mc:Ignorable="d">
        <Style x:Key="TextBlockStyle1" TargetType="{x:Type TextBlock}">
            <Setter Property="TextWrapping" Value="NoWrap"/>
            <Setter Property="TextTrimming" Value="None"/>
            <Setter Property="Margin" Value="10,2"/>
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Height" Value="40"/>
        </Style>
        <SolidColorBrush x:Key="TextBox.Static.Border" Color="Red"/>
        <SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="Gainsboro"/>
        <SolidColorBrush x:Key="TextBox.Focus.Border" Color="Blue"/>
        <Style x:Key="TextBoxStyle1" TargetType="{x:Type TextBox}">
            <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
            <Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="BorderThickness" Value="2"/>
            <Setter Property="Height" Value="40"/>
            <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="AllowDrop" Value="False"/>
            <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
            <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TextBox}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                            <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" Width="95" Height="15" HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontStretch="Expanded" FlowDirection="RightToLeft"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Opacity" TargetName="border" Value="0.5"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.MouseOver.Border}"/>
                            </Trigger>
                            <Trigger Property="IsKeyboardFocused" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.Focus.Border}"/>
                            </Trigger>
                            
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsInactiveSelectionHighlightEnabled" Value="true"/>
                        <Condition Property="IsSelectionActive" Value="false"/>
                    </MultiTrigger.Conditions>
                    <Setter Property="SelectionBrush" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightBrushKey}}"/>
                </MultiTrigger>
            </Style.Triggers>
        </Style>
    </ResourceDictionary>
    
    Model:
    using CommunityToolkit.Mvvm.ComponentModel;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    
    namespace CommunityToolkitMVVM.Models
    {
        public class Model : ObservableObject
        {
            //求和a+b=c
            private int a;
            public int A
            {
                get => a;
                set => SetProperty(ref a, value);
            }
            private int b;
            public int B
            {
                get => b;
                set => SetProperty(ref b, value);
            }
    
            private int c;
            public int C
            {
                get => c;
                set => SetProperty(ref c, value); 
            }
    
            private bool isStart;
    
            public bool IsStart
            {
                get => isStart;
                set => SetProperty(ref isStart, value);
            }
        }
    
        public class AnimateDP: DependencyObject
        {
            public bool AnimateStart
            {
                get { return (bool)GetValue(AnimateStartProperty); }
                set { SetValue(AnimateStartProperty, value); }
            }
    
            public static readonly DependencyProperty AnimateStartProperty =  DependencyProperty.Register("AnimateStart", typeof(bool), typeof(AnimateDP), new PropertyMetadata(true));
        }
    }
    
    
    ViewModel:
    using CommunityToolkitMVVM.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using CommunityToolkit.Mvvm.ComponentModel;
    using CommunityToolkit.Mvvm.Input;
    namespace CommunityToolkitMVVM.ViewModels
    {
        public class MainViewModel : ObservableObject
        {
            public Model calculateModel { get; set; }=new Model() {  A=0, B=0, C=0, IsStart=false};
            public AnimateDP AnimateDP { get; set; } = new AnimateDP() { AnimateStart = false };
            public MainViewModel()
            {          
                MyButtonCommand = new RelayCommand(() => AnimateDP.AnimateStart = true) ;
            }
            private RelayCommand myButtonCommand;
    
            public RelayCommand MyButtonCommand
            {
                get { return myButtonCommand; }
                set { myButtonCommand = value; }
            }
        }
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 1月1日

悬赏问题

  • ¥15 单纯型python实现编译报错
  • ¥15 c++2013读写oracle
  • ¥15 c++ gmssl sm2验签demo
  • ¥15 关于模的完全剩余系(关键词-数学方法)
  • ¥15 有没有人懂这个博图程序怎么写,还要跟SFB连接,真的不会,求帮助
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音