WPF Animate border background color - wpf

I'm trying to animate the color of the brush for the background of a custom class that inherits from Border. I've tried the MSDN link here:
http://msdn.microsoft.com/en-us/library/system.windows.media.animation.coloranimation.aspx
This is not exactly what I'm looking for, but can get me to a point with no errors but still, nothing is animating. The problem with the example is that they are defining the logic within a class that isn't the rectangle. I am trying to define from within the rectangle (actually the border).
Below is my code that I tried to extrapolate from MSDN for my situation.
public class PrettyButton : System.Windows.Controls.Border
{
private System.Windows.Media.SolidColorBrush hoverColor = new System.Windows.Media.SolidColorBrush();
private System.Windows.Media.SolidColorBrush origColor = new System.Windows.Media.SolidColorBrush();
private System.Windows.Media.Animation.Storyboard story = new System.Windows.Media.Animation.Storyboard();
public PrettyButton()
{
hoverColor.Color = System.Windows.Media.Color.FromArgb(255, 50, 200, 0);
origColor.Color = System.Windows.Media.Color.FromArgb(0, 0, 0, 0);
this.MouseEnter += PrettyButton_MouseEnter;
this.MouseLeave += PrettyButton_MouseLeave;
//Animate in logic
System.Windows.Media.Animation.ColorAnimation color = new System.Windows.Media.Animation.ColorAnimation(hoverColor.Color, System.TimeSpan.FromMilliseconds(400));
System.Windows.Media.Animation.Storyboard.SetTargetProperty(color, new System.Windows.PropertyPath(System.Windows.Media.SolidColorBrush.ColorProperty));
story.Children.Add(color);
}
and below in the mouseEvent I have
void PrettyButton_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
story.Begin(this);
}
Unfortunately, I'm not getting any more errors so the trail has gone cold for me. I am also certain that I could probably find 10 solutions in XAML, but I would like for this class to be reusable in the future, and redefining this logic is not ideal.

Instead of System.Windows.Media.SolidColorBrush.ColorProperty, try setting "(Border.Background).(SolidColorBrush.Color)"
Property Path.
System.Windows.Media.Animation.Storyboard.SetTargetProperty(color, new System.Windows.PropertyPath("(Border.Background).(SolidColorBrush.Color)"));
Also set Background in constructor of PrettyButton as like this :
public PrettyButton()
{
.....
origColor.Color = System.Windows.Media.Color.FromArgb(0, 0, 0, 0);
this.Background= new SolidColorBrush(origColor.Color);
..
....
}
UPDATE :
public class PrettyButton : System.Windows.Controls.Border
{
private System.Windows.Media.SolidColorBrush hoverColor = new System.Windows.Media.SolidColorBrush();
private System.Windows.Media.SolidColorBrush origColor = new System.Windows.Media.SolidColorBrush();
public PrettyButton()
{
hoverColor.Color = System.Windows.Media.Color.FromArgb(255, 50, 200, 0);
origColor.Color = System.Windows.Media.Color.FromArgb(0, 0, 0, 0);
this.Background= new SolidColorBrush(origColor.Color);
this.MouseEnter += PrettyButton_MouseEnter;
this.MouseLeave += PrettyButton_MouseLeave;
}
private void PrettyButton_MouseLeave(object sender, MouseEventArgs e)
{
System.Windows.Media.Animation.Storyboard story = new System.Windows.Media.Animation.Storyboard();
System.Windows.Media.Animation.ColorAnimation color = new System.Windows.Media.Animation.ColorAnimation(origColor.Color, System.TimeSpan.FromMilliseconds(400));
System.Windows.Media.Animation.Storyboard.SetTargetProperty(color, new System.Windows.PropertyPath("(Border.Background).(SolidColorBrush.Color)"));
story.Children.Add(color);
story.Begin(this);
}
private void PrettyButton_MouseEnter(object sender, MouseEventArgs e)
{
System.Windows.Media.Animation.Storyboard story = new System.Windows.Media.Animation.Storyboard();
System.Windows.Media.Animation.ColorAnimation color = new System.Windows.Media.Animation.ColorAnimation(hoverColor.Color, System.TimeSpan.FromMilliseconds(400));
System.Windows.Media.Animation.Storyboard.SetTargetProperty(color, new System.Windows.PropertyPath("(Border.Background).(SolidColorBrush.Color)"));
story.Children.Add(color);
story.Begin(this);
}
}

Related

Core 3.0 WinForms ListView not propogating events

Created a Core 3.0 Winforms project.
I have no issues with button clicks etc however the Listview doesn't send any events like click.
I used the sample found here, that seems to work okey, however my events on a Listview are not happening.
Even a simple assignment in the forms constructor is not Propagation.
public Form1()
{
ListViewControlItems.Click += ListViewControlItems_Click;
}
private void ListViewControlItems_Click( object sender, EventArgs e)
{
throw new NotImplementedException();
}
I can click all like, no exception, no brakepoint gets hit.
Source can be downloaded here
so Tobias found a work arround for the bug in GitHub. Looks like that, for now, you may get an issue when you alter the ListView in the constructor of the form.
After I moved the initialization of the Listview in the form from the constructor to the Load event the issue of it not firing events was solved.
From BAD!
public Form1()
{
InitializeComponent();
columnWidths = new Dictionary<string, int>
{
["DirectoryName"] = 150,
["TrainingError"] = 150
};
columnAlighnments = new Dictionary<string, HorizontalAlignment>
{
["DirectoryName"] = HorizontalAlignment.Left,
["NetworkConfiguration"] = HorizontalAlignment.Left
};
ListViewControlItems.Columns.Clear();
foreach (string columnName in ListViewHeaders())
{
ListViewControlItems.Columns.Add(columnName
, width: columnWidths.TryGetValue(columnName, out int i) ? i : 50
, textAlign: columnAlighnments.TryGetValue(columnName, out HorizontalAlignment a) ? a : HorizontalAlignment.Right);
}
ListViewControlItems.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
ListViewControlItems.SelectedIndexChanged += OnSelectedTrainingFileChanged;
fileSorter = new ListViewColumnSorterExt(ListViewControlItems);
}
to work around:
public Form1()
{
InitializeComponent();
columnWidths = new Dictionary<string, int>
{
["DirectoryName"] = 150,
["TrainingError"] = 150
};
columnAlighnments = new Dictionary<string, HorizontalAlignment>
{
["DirectoryName"] = HorizontalAlignment.Left,
["NetworkConfiguration"] = HorizontalAlignment.Left
};
Load += OnFormLoaded;
}
private void OnFormLoaded(object sender, EventArgs e)
{
ListViewControlItems.Columns.Clear();
foreach (string columnName in ListViewHeaders())
{
ListViewControlItems.Columns.Add(columnName
, width: columnWidths.TryGetValue(columnName, out int i) ? i : 50
, textAlign: columnAlighnments.TryGetValue(columnName, out HorizontalAlignment a) ? a : HorizontalAlignment.Right);
}
ListViewControlItems.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
ListViewControlItems.SelectedIndexChanged += OnSelectedTrainingFileChanged;
fileSorter = new ListViewColumnSorterExt(ListViewControlItems);
}

How to draw dropshadow effect in a geometry in WPF

I'm drawing the following Shape in a Canvas.
I would like to highlight it when it's selected by changing its color (the easy part) and drawing an small halo around it:
This is how I did using SASS: http://codepen.io/aaromnido/pen/zKvAwd/
How coud I draw in WPF? Remember that I'm drawing using the Shape's OnRender method.
Set some defaults in constructor.
One of these defaults is Shape.Effect, as it will be animated on MouseEnter event.
Construct VisualStates for Normal , and MouseEnter scenarios.
Change the VisualState of the element using VisualStateManager.GoToElementState() in MouseEnter and MouseLeave event handlers.
You can expose various properties using DPs for customization.
NewShape.cs
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows;
using System.Windows.Media.Effects;
namespace WpfStackOverflow.NewShape
{
public class CNewShape : Shape
{
public CNewShape()
{
// setting the defaults
this.Width = 40;
this.Height = 40;
this.Stroke = new SolidColorBrush() { Color = Colors.Red };
this.StrokeThickness = 5;
this.Effect = new DropShadowEffect() {
Color = Colors.Transparent,
BlurRadius = 1,
Direction = -150,
ShadowDepth = 1
};
// constructing the VisualStates
_constructVisualStates();
// event handlers
this.MouseEnter += CNewShape_MouseEnter;
this.MouseLeave += CNewShape_MouseLeave;
}
#region EventHandlers
void CNewShape_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
VisualStateManager.GoToElementState(this, "VSNormal", false);
}
void CNewShape_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
VisualStateManager.GoToElementState(this, "VSMouseEnter", false);
}
#endregion
#region Overrides
// This needs to be implemented as it is abstract in base class
GeometryGroup geo = new GeometryGroup();
protected override Geometry DefiningGeometry
{
get { return geo; }
}
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
Pen pen = new Pen(this.Stroke, StrokeThickness);
drawingContext.DrawEllipse(Brushes.Transparent, pen, new Point(Width/2, Height/2), 40, 40);
drawingContext.DrawEllipse(Stroke, null, new Point(Width / 2, Height / 2), 30, 30);
base.OnRender(drawingContext);
}
#endregion
#region Helpers
private void _constructVisualStates()
{
VisualStateGroup vsg1 = new VisualStateGroup();
#region VSNormal (Normal Visual State)
VisualState stateVSNormal = new VisualState() { Name = "VSNormal" };
Storyboard sbVSNormal = new Storyboard();
ObjectAnimationUsingKeyFrames oa = new ObjectAnimationUsingKeyFrames();
Storyboard.SetTargetProperty(oa, new PropertyPath("Effect"));
DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame(null);
oa.KeyFrames.Add(dokf);
sbVSNormal.Children.Add(oa);
stateVSNormal.Storyboard = sbVSNormal;
vsg1.States.Add(stateVSNormal);
#endregion
#region VSMouseEnter (MouseEnter Visual State)
VisualState stateVSMouseEnter = new VisualState() { Name = "VSMouseEnter" };
Storyboard sbVSMouseEnter = new Storyboard();
ColorAnimation caStrokeColor = new ColorAnimation();
caStrokeColor.To = (Color)ColorConverter.ConvertFromString("#FF24BCDE");
Storyboard.SetTargetProperty(caStrokeColor, new PropertyPath("(Shape.Stroke).(SolidColorBrush.Color)"));
sbVSMouseEnter.Children.Add(caStrokeColor);
ColorAnimation caEffectColor = new ColorAnimation();
caEffectColor.To = (Color)ColorConverter.ConvertFromString("#FFA4E1F3");
Storyboard.SetTargetProperty(caEffectColor, new PropertyPath("(Shape.Effect).(Color)"));
sbVSMouseEnter.Children.Add(caEffectColor);
DoubleAnimation daBlurRadius = new DoubleAnimation();
daBlurRadius.To = 10;
Storyboard.SetTargetProperty(daBlurRadius, new PropertyPath("(Shape.Effect).(BlurRadius)"));
sbVSMouseEnter.Children.Add(daBlurRadius);
DoubleAnimation daDirection = new DoubleAnimation();
daDirection.To = -190;
Storyboard.SetTargetProperty(daDirection, new PropertyPath("(Shape.Effect).(Direction)"));
sbVSMouseEnter.Children.Add(daDirection);
stateVSMouseEnter.Storyboard = sbVSMouseEnter;
vsg1.States.Add(stateVSMouseEnter);
#endregion
VisualStateManager.GetVisualStateGroups(this).Add(vsg1);
}
#endregion
}
}
Usage
<local:CNewShape Canvas.Left="70" Canvas.Top="52" Stroke="#FF374095" StrokeThickness="10" Width="100" Height="100" />
Output
Quality of the image is bad. On screen actual output looks good.
Whatever your trigger is that your control enters the Highlighted state, in that trigger just set the Effect property. For my test the "trigger" is a property:
public static readonly DependencyProperty ShowShadowProperty =
DependencyProperty.Register ("ShowShadow", typeof (bool), typeof (TestShape), new PropertyMetadata (false, ShowShadowChanged));
public bool ShowShadow
{
get { return (bool)GetValue (ShowShadowProperty); }
set { SetValue (ShowShadowProperty, value); }
}
private static void ShowShadowChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TestShape)d).OnShowShadow ();
}
private void OnShowShadow ()
{
if (ShowShadow)
{
Effect = new DropShadowEffect { Direction = 0, ShadowDepth = 20, BlurRadius = 33, Opacity = 1, Color = Colors.Black};
}
else
{
Effect = null;
}
}
Which means you don't need to do anything in OnRender.

Quickest way to hide an array of pictureboxes

I have an array of pictureboxes named from B11 (co-ords 1,1) to B55 (co-ords 5,5). I would like to hide these all on startup (and in the middle of running). I was thinking of making an array of the names manually but would it be the best solution?
If they all have a common parent control, such as a panel or groupbox (or even the form):
Parent.SuspendLayout()
For Each pbox As PictureBox in Parent.Controls.OfType(Of PictureBox)()
pbox.Visible = False
Next pbox
Parent.ResumeLayout()
The Suspend/Resume-Layout() is to avoid flickering as you modify a bunch of controls at once.
You could extend the PictureBox class and use event handling to accomplish this by:
Adding a public property to the form to tell if the picture boxes should be shown or hidden.
Adding an event to the form that is raised when the show/hide picture box property is changed.
Extending the PictureBox class so that it subscribes to the event of the parent form.
Setting the visible property of the extended PictureBox class to the show/hide property of the parent form.
When the show/hide flag is changed on the parent form all of the picture boxes will change their visibility property accordingly.
Form Code:
public partial class PictureBoxForm : Form {
public PictureBoxForm() {
InitializeComponent();
this.pictureBoxesAdd();
}
private void pictureBoxesAdd() {
MyPictureBox mp1 = new MyPictureBox();
mp1.Location = new Point(1, 1);
MyPictureBox mp2 = new MyPictureBox();
mp2.Location = new Point(200, 1);
this.Controls.Add(mp1);
this.Controls.Add(mp2);
}
public event EventHandler PictureBoxShowFlagChanged;
public bool PictureBoxShowFlag {
get { return this.pictureBoxShowFlag; }
set {
if (this.pictureBoxShowFlag != value) {
pictureBoxShowFlag = value;
if (this.PictureBoxShowFlagChanged != null) {
this.PictureBoxShowFlagChanged(this, new EventArgs());
}
}
}
}
private bool pictureBoxShowFlag = true;
private void cmdFlip_Click( object sender, EventArgs e ) {
this.PictureBoxShowFlag = !this.PictureBoxShowFlag;
}
}
Extended PictureBox Code:
public class MyPictureBox : PictureBox {
public MyPictureBox() : base() {
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ParentChanged += new EventHandler(MyPictureBox_ParentChanged);
}
private void MyPictureBox_ParentChanged( object sender, EventArgs e ) {
try {
PictureBoxForm pbf = (PictureBoxForm)this.Parent;
this.Visible = pbf.PictureBoxShowFlag;
pbf.PictureBoxShowFlagChanged += new
EventHandler(pbf_PictureBoxShowFlagChanged);
} catch { }
}
private void pbf_PictureBoxShowFlagChanged( object sender, EventArgs e ) {
PictureBoxForm pbf = (PictureBoxForm)sender;
this.Visible = pbf.PictureBoxShowFlag;
}
}
...or just put 'em all on a Panel, and change the panel's visibility.

GridLength animation using keyframes?

I want to know are there any classes that I can animate a GridLength value using KeyFrames? I have seen the following sites, but none of them were with KeyFrames:
http://windowsclient.net/learn/video.aspx?v=70654
http://marlongrech.wordpress.com/2007/08/20/gridlength-animation/
Any advice?
Create an attached behavior and animate it instead.
Sure, GridLength clearly is not a numeric type and as such it's not clear how it can be animated. To compnesate that I can create an attached behavior like:
public class AnimatableProperties
{
public static readonly DependencyProperty WidthProperty =
DependencyProperty.RegisterAttached("Width",
typeof(double),
typeof(DependencyObject),
new PropertyMetadata(-1, (o, e) =>
{
AnimatableProperties.OnWidthChanged((Grid)o, (double)e.NewValue);
}));
public static void SetWidth(DependencyObject o,
double e)
{
o.SetValue(AnimatableProperties.WidthProperty, e);
}
public static double GetWidth(DependencyObject o)
{
return (double)o.GetValue(AnimatableProperties.WidthProperty);
}
private static void OnWidthChanged(DependencyObject target,
double e)
{
target.SetValue(Grid.WidthProperty, new GridLength(e));
}
}
That will re-inroduce Grid width as numeric property of double type. Having that in place you can freely animate it.
P.S. Obviously it doesn't make much sense to use Grid's Width as it's already double. any other GridLength based properties can be wrpapped with double wrappers as per the sample above and then animated via that wrappers.
It is fairly straight forward but you need to use an adapter because you can't directly animate Width on the ColumnDefinition class with a DoubleAnimator because ColumnDefinition is not a double. Here's my code:
public class ColumnDefinitionDoubleAnimationAdapter : Control
{
#region Dependency Properties
public static readonly DependencyProperty WidthProperty = DependencyProperty.Register(nameof(Width), typeof(double), typeof(ColumnDefinitionDoubleAnimationAdapter), new PropertyMetadata((double)0, WidthChanged));
private static void WidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var columnDefinitionDoubleAnimationAdapter = (ColumnDefinitionDoubleAnimationAdapter)d;
columnDefinitionDoubleAnimationAdapter.Width = (double)e.NewValue;
}
#endregion
#region Fields
private ColumnDefinition _ColumnDefinition;
#endregion
#region Constructor
public ColumnDefinitionDoubleAnimationAdapter(ColumnDefinition columnDefinition)
{
_ColumnDefinition = columnDefinition;
}
#endregion
#region Public Properties
public double Width
{
get
{
return (double)GetValue(WidthProperty);
}
set
{
SetValue(WidthProperty, value);
_ColumnDefinition.Width = new GridLength(value);
}
}
#endregion
}
Unfortunately the above is pretty inefficient because it creates a GridLength again and again because ColumnDefinition.Width.Value should be read only.
Here is a method to do the animation. It's important that it uses Task based async because otherwise the storyboard will go out of scope and cause bad behaviour. This is good practice anyway so you can await the animation if you need to:
public async static Task AnimateColumnWidth(ColumnDefinition columnDefinition, double from, double to, TimeSpan duration, IEasingFunction ease)
{
var taskCompletionSource = new TaskCompletionSource<bool>();
var storyboard = new Storyboard();
var animation = new DoubleAnimation();
animation.EasingFunction = ease;
animation.Duration = new Duration(duration);
storyboard.Children.Add(animation);
animation.From = from;
animation.To = to;
var columnDefinitionDoubleAnimationAdapter = new ColumnDefinitionDoubleAnimationAdapter(columnDefinition);
Storyboard.SetTarget(animation, columnDefinitionDoubleAnimationAdapter);
Storyboard.SetTargetProperty(animation, new PropertyPath(ColumnDefinitionDoubleAnimationAdapter.WidthProperty));
storyboard.Completed += (a, b) =>
{
taskCompletionSource.SetResult(true);
};
storyboard.Begin();
await taskCompletionSource.Task;
}
And an example usage:
private async void TheMenu_HamburgerToggled(object sender, EventArgs e)
{
TheMenu.IsOpen = !TheMenu.IsOpen;
var twoSeconds = TimeSpan.FromMilliseconds(120);
var ease = new CircleEase { EasingMode = TheMenu.IsOpen ? EasingMode.EaseIn : EasingMode.EaseOut };
if (TheMenu.IsOpen)
{
await UIUtilities.AnimateColumnWidth(MenuColumn, 40, 320, twoSeconds, ease);
}
else
{
await UIUtilities.AnimateColumnWidth(MenuColumn, 320, 40, twoSeconds, ease);
}
}

WPF - sequential animation simple example

I'm learning about WPF animation, and am confused about how to apply animations sequentially. As a simple example, I've got four rectangles in a uniform grid, and would like to change the color of each one sequentially. Here's what I have so far:
public partial class Window1 : Window
{
Rectangle blueRect;
Rectangle redRect;
Rectangle greenRect;
Rectangle yellowRect;
public Window1()
{
InitializeComponent();
blueRect = new Rectangle() { Fill = System.Windows.Media.Brushes.Blue, Name="Blue"};
redRect = new Rectangle() { Fill = System.Windows.Media.Brushes.Red, Name="Yellow"};
greenRect = new Rectangle() { Fill = System.Windows.Media.Brushes.Green, Name="Green" };
yellowRect = new Rectangle() { Fill = System.Windows.Media.Brushes.Yellow, Name="Yellow" };
UniformGrid1.Children.Add(blueRect);
UniformGrid1.Children.Add(redRect);
UniformGrid1.Children.Add(greenRect);
UniformGrid1.Children.Add(yellowRect);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
animateCell(blueRect, Colors.Blue);
animateCell(redRect, Colors.Red);
}
private void animateCell(Rectangle rectangle, Color fromColor)
{
Color toColor = Colors.White;
ColorAnimation ani = new ColorAnimation(toColor, new Duration(TimeSpan.FromMilliseconds(300)));
ani.AutoReverse = true;
SolidColorBrush newBrush = new SolidColorBrush(fromColor);
ani.BeginTime = TimeSpan.FromSeconds(2);
rectangle.Fill = newBrush;
newBrush.BeginAnimation(SolidColorBrush.ColorProperty, ani);
//NameScope.GetNameScope(this).RegisterName(rectangle.Name, rectangle);
//Storyboard board = new Storyboard();
//board.Children.Add(ani);
//Storyboard.SetTargetName(rectangle, rectangle.Name);
//Storyboard.SetTargetProperty(ani, new PropertyPath(SolidColorBrush.ColorProperty));
//board.Begin();
}
What's the easiest way of accomplishing this? The code in the comments is my first guess, but it's not working correctly.
There should be an event ani.Completed - handle that event and start the next phase of the animation, then start the first one running and each phase will trigger the next.
ColorAnimation ani = // whatever...
ani.Completed += (s, e) =>
{
ColorAnimation ani2 = // another one...
// and so on
};
newBrush.BeginAnimation(SolidColorBrush.ColorProperty, ani);
UPDATE:
public partial class Window1 : Window
{
Rectangle blueRect;
Rectangle redRect;
Rectangle greenRect;
Rectangle yellowRect;
public Window1()
{
InitializeComponent();
blueRect = new Rectangle() { Fill = System.Windows.Media.Brushes.Blue, Name = "Blue" };
redRect = new Rectangle() { Fill = System.Windows.Media.Brushes.Red, Name = "Yellow" };
greenRect = new Rectangle() { Fill = System.Windows.Media.Brushes.Green, Name = "Green" };
yellowRect = new Rectangle() { Fill = System.Windows.Media.Brushes.Yellow, Name = "Yellow" };
UniformGrid1.Children.Add(blueRect);
UniformGrid1.Children.Add(redRect);
UniformGrid1.Children.Add(greenRect);
UniformGrid1.Children.Add(yellowRect);
}
IEnumerable<Action<Action>> AnimationSequence()
{
for (; ; )
{
yield return AnimateCell(blueRect, Colors.Blue);
yield return AnimateCell(redRect, Colors.Red);
yield return AnimateCell(greenRect, Colors.Green);
yield return AnimateCell(yellowRect, Colors.Yellow);
}
}
private IEnumerator<Action<Action>> _actions;
private void RunNextAction()
{
if (_actions.MoveNext())
_actions.Current(RunNextAction);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_actions = AnimationSequence().GetEnumerator();
RunNextAction();
}
private Action<Action> AnimateCell(Rectangle rectangle, Color fromColor)
{
return completed =>
{
Color toColor = Colors.White;
ColorAnimation ani = new ColorAnimation(toColor,
new Duration(TimeSpan.FromMilliseconds(300)));
ani.AutoReverse = true;
ani.Completed += (s, e) => completed();
SolidColorBrush newBrush = new SolidColorBrush(fromColor);
ani.BeginTime = TimeSpan.FromSeconds(2);
rectangle.Fill = newBrush;
newBrush.BeginAnimation(SolidColorBrush.ColorProperty, ani);
};
}
}
Try pasting the above into your program. It does what you need, but in a way that may be useful to you in other contexts. It's still event driven, but it uses an "iterator method" (with yield return) to create the impression that it is sequential coding that blocks while the animation is going on.
The nice thing about this is that you can play around with the AnimationSequence method in a very intuitive way - you could write out the timeline of the animation in a series of statements, or use loops, or whatever you want.
The solution I've tried is to use a Queue like so. This will let you add to the animation chain dynamically. I'm not sure if the lock is necessary, but I left it in just to be safe.
Queue<Object[]> animationQueue = new Queue<Object[]>();
void sequentialAnimation(DoubleAnimation da, Animatable a, DependencyProperty dp)
{
da.Completed += new EventHandler(da_Completed);
lock (animationQueue)
{
if (animationQueue.Count == 0) // no animation pending
{
animationQueue.Enqueue(new Object[] { da, a, dp });
a.BeginAnimation(dp, da);
}
else
{
animationQueue.Enqueue(new Object[] { da, a, dp });
}
}
}
void da_Completed(object sender, EventArgs e)
{
lock (animationQueue)
{
Object[] completed = animationQueue.Dequeue();
if (animationQueue.Count > 0)
{
Object[] next = animationQueue.Peek();
DoubleAnimation da = (DoubleAnimation)next[0];
Animatable a = (Animatable)next[1];
DependencyProperty dp = (DependencyProperty)next[2];
a.BeginAnimation(dp, da);
}
}
}
This can be accomplished by using a class with the contradictory name ParallelTimeline and carefully adjusting the BeginTime property. Note in the example below how the BeginTime property of the second DoubleAnimation is set to the duration of the first.
<ParallelTimeline>
<DoubleAnimation
Storyboard.TargetName="FlashRectangle"
Storyboard.TargetProperty="Opacity"
From="0.0" To="1.0" Duration="0:0:1"/>
<DoubleAnimation BeginTime="0:0:0.05"
Storyboard.TargetName="FlashRectangle"
Storyboard.TargetProperty="Opacity"
From="1.0" To="0.0" Duration="0:0:2"/>
</ParallelTimeline>

Resources