1 public class BlinkAnimation : Animatable 2 { 3 /// <summary> 4 /// 单例,保持所有闪烁的动画同步 5 /// </summary> 6 public static readonly BlinkAnimation Instance = new BlinkAnimation(); 7 8 public double BlinkOpacity 9 { 10 get { return (double)GetValue(BlinkOpacityProperty); } 11 set { SetValue(BlinkOpacityProperty, value); } 12 } 13 14 // Using a DependencyProperty as the backing store for BlinkOpacity. This enables animation, styling, binding, etc... 15 public static readonly DependencyProperty BlinkOpacityProperty = 16 DependencyProperty.Register("BlinkOpacity", typeof(double), typeof(BlinkAnimation), new PropertyMetadata(0.0)); 17 18 19 20 /// <summary> 21 /// 闪烁动画,用于动画同步 22 /// </summary> 23 public BlinkAnimation() 24 { 25 try 26 { 27 DoubleAnimationUsingKeyFrames doubleAnimation = new DoubleAnimationUsingKeyFrames 28 { 29 RepeatBehavior = RepeatBehavior.Forever, 30 Duration = TimeSpan.FromSeconds(1.5) 31 }; 32 33 DiscreteDoubleKeyFrame ddkf1 = new DiscreteDoubleKeyFrame(0.0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0))); 34 DiscreteDoubleKeyFrame ddkf2 = new DiscreteDoubleKeyFrame(1.0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.75))); 35 36 doubleAnimation.KeyFrames.Add(ddkf1); 37 doubleAnimation.KeyFrames.Add(ddkf2); 38 39 if (BlinkOpacityProperty!=null) 40 { 41 BeginAnimation(BlinkOpacityProperty, doubleAnimation); 42 } 43 } 44 catch (Exception) 45 { 46 // ignored 47 } 48 } 49 50 protected override Freezable CreateInstanceCore() 51 { 52 return Instance; 53 } 54 }
使用方法:
1 <!--闪烁动画同步控制类--> 2 <ObjectDataProvider x:Key="BlinkerOdp" 3 ObjectType="{x:Type animation:BlinkAnimation}" />
1 <Rectangle Fill="White" 2 DataContext="{StaticResource BlinkerOdp}" 3 Opacity="{Binding BlinkOpacity}" 4 x:Name="rect" 5 Visibility="Collapsed" />
感谢阅读