[英]Why doesn't this storyboard defined in code work?
我正在嘗試為GradientBrush
創建一個動畫,該動畫將為每個漸變設置動畫,以無限期地循環遍歷漸變中包含的所有顏色。
由於這項任務的復雜性,我已經開始處理代碼中的所有內容,而不是XAML。
幸運的是,我的代碼沒有錯誤或異常。
不幸的是,它也一無所獲。
符合最小,完整和可驗證的示例要求:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace MCVE {
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class Program {
private static LinearGradientBrush TestBrush { get; } =
new LinearGradientBrush(
new GradientStopCollection( new[ ]{
new GradientStop( Colors.Black, 0 / 1.0D ),
new GradientStop( Colors.White, 1 / 1.0D )
} ), new Point( 0.0D, 0.0D ), new Point( 1.0D, 1.0D ) );
[STAThread]
public static int Main( ) {
Storyboard board = CreateStoryboard( TestBrush );
Window w = new Window( ){
Background = TestBrush
};
w.Loaded += new RoutedEventHandler(
( S, E ) => board.Begin( w, true ) );
Program program = new Program( );
program.InitializeComponent( );
return program.Run( w );
}
public static Storyboard CreateStoryboard( GradientBrush brush ) {
Storyboard board = new Storyboard( ){
Duration = new Duration( TimeSpan.FromSeconds( 1.0D ) ),
RepeatBehavior = RepeatBehavior.Forever
};
foreach (
var animation
in brush.GradientStops.Select(
GS => _CreateGradientStopAnimation(
GS, brush.GradientStops.SkipWhile( G => G != GS
).Concat( brush.GradientStops.TakeWhile( G => G != GS )
).Concat( new[ ] { GS } ).Select( G => G.Color ) ) ) )
board.Children.Add( animation );
return board;
ColorAnimationUsingKeyFrames _CreateGradientStopAnimation(
GradientStop stop, IEnumerable<Color> colors ) {
ColorAnimationUsingKeyFrames animation =
new ColorAnimationUsingKeyFrames( );
Storyboard.SetTarget( animation, stop );
Storyboard.SetTargetProperty(
animation, new PropertyPath(
GradientStop.ColorProperty ) );
foreach ( var keyFrame in colors.Select(
C => new EasingColorKeyFrame( C ) ) )
animation.KeyFrames.Add( keyFrame );
return animation;
}
}
}
}
我已經嘗試僅對ColorAnimationUsingKeyFrames
中的每個漸變使用ColorAnimationUsingKeyFrames
,並且DOES有效,但我更喜歡使用Storyboard
(如果可能),以便所有動畫可以一起啟動。
我正在嘗試做什么? 如果是這樣,我做錯了什么?
如果沒有,我該怎么做才能完成我想在這里完成的任務(同時啟動許多不同的動畫)?
不知道究竟是什么問題,但凍結故事板似乎已經足夠了:
var storyboard = CreateStoryboard(TestBrush);
storyboard.Freeze();
Loaded += (s, e) => storyboard.Begin();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.