記錄一種實現方式:
第一步:
首先定義一個靜態類,提供依賴屬性,進而方便在xaml中實現綁定:
public static class AnimationBehavior{// 定義附加屬性public static readonly DependencyProperty IsAnimatingProperty =DependencyProperty.RegisterAttached("IsAnimating",typeof(bool),typeof(AnimationBehavior),new PropertyMetadata(false, OnIsAnimatingChanged));public static bool GetIsAnimating(DependencyObject obj) =>(bool)obj.GetValue(IsAnimatingProperty);public static void SetIsAnimating(DependencyObject obj, bool value) =>obj.SetValue(IsAnimatingProperty, value);private static void OnIsAnimatingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){if (d is FrameworkElement element){// 通過 VisualTreeHelper 查找模板中的 Storyboardif (element.FindResource("ShadowAnimation") is Storyboard storyboard){if ((bool)e.NewValue)storyboard.Begin(element, true); // 啟動動畫elsestoryboard.Stop(element); // 停止動畫}}}}
其中實現了依賴屬性IsAnimating。
第二步:
在前端中定義動畫:
<Page.Resources><!-- 將 Storyboard 定義在全局資源中 --><Storyboard x:Key="ShadowAnimation"><DoubleAnimationAutoReverse="True"RepeatBehavior="Forever"Storyboard.TargetName="ShadowEffect"Storyboard.TargetProperty="Opacity"From="0.0"To="1"Duration="0:0:3" /><DoubleAnimationAutoReverse="True"RepeatBehavior="Forever"Storyboard.TargetName="myBorder"Storyboard.TargetProperty="Opacity"From="0.3"To="1"Duration="0:0:3" /><!--<ThicknessAnimationAutoReverse="True"RepeatBehavior="Forever"Storyboard.TargetName="myBorder"Storyboard.TargetProperty="Margin"From="15"To="12"Duration="0:0:1.5" />--></Storyboard></Page.Resources>
其中每一個DoubleAnimation定義中的TargetName是當前界面的其他對象名稱:
<Borderx:Name="myBorder"Grid.ColumnSpan="1"Margin="4"localVM:AnimationBehavior.IsAnimating="{Binding CurrentActionHandle.ExecutionState, Converter={StaticResource SingleFlowExecutionStateToBoolJustRunnimg}}"Background="{Binding CurrentActionHandle.ExecutionState, Converter={StaticResource SingleFlowExecutionStateToBrushColor}}"CornerRadius="10"><Border.Effect><DropShadowEffectx:Name="ShadowEffect"BlurRadius="10"Direction="12"Opacity="80"ShadowDepth="0"Color="{Binding CurrentActionHandle.ExecutionState, Converter={StaticResource SingleFlowExecutionStateToColor}}" /></Border.Effect></Border>
比如myBorder 和 ShadowEffect;?
第三步:
創建綁定關系:
比如上方代碼中:
localVM:AnimationBehavior.IsAnimating="{Binding CurrentActionHandle.ExecutionState, Converter={StaticResource SingleFlowExecutionStateToBoolJustRunnimg}}"
給新手解釋一下,其中localVM是自己定義的命名空間:
?
可我這里使用了轉換器,可以理解為就是把執行動畫的開關綁定到了我后端ViewModel的屬性上。