I need help in taking right decision. I need to animate a background color of my user control when some event happens. When it is, I want to change the background just for 1 second and then turn it back. Which way should I go? Use color animation or timer or may by some other way.
Solved. Thanks to all! This works good for me:
ColorAnimation animation;
animation = new ColorAnimation();
animation.From = Colors.Orange;
animation.To = Colors.Gray;
animation.Duration = new Duration(TimeSpan.FromSeconds(1));
this.elGrid.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation);
I would use an EventTrigger
with a ColorAnimation
.
In this example a Button Brackground
goes green on a MouseLeave
event. This code is hopefully similar to what you may need.
<Button Content="Button" Height="75" HorizontalAlignment="Left" Margin="27,12,0,0" Name="btnImgBrush" VerticalAlignment="Top" Width="160" Background="LightGray">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.MouseLeave">
<BeginStoryboard>
<Storyboard>
<ColorAnimation To="Green"
Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
FillBehavior="Stop"
Duration="0:0:1"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
Watch out, you could received a System.InvalidOperationException if your background is a frozen instance.
Cannot animate the 'Color' property on 'System.Windows.Media.SolidColorBrush' because the object is sealed or frozen.
To correct this message assign the background of your control to a non-frozen instance.
// Do not use a frozen instance
this.elGrid.Background = new SolidColorBrush(Colors.Orange);
this.elGrid.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation);
Freezable Objects Overview on MSDN
ColorAnimation colorChangeAnimation = new ColorAnimation();
colorChangeAnimation.From = VariableColour;
colorChangeAnimation.To = BaseColour;
colorChangeAnimation.Duration = timeSpan;
PropertyPath colorTargetPath = new PropertyPath("(Panel.Background).(SolidColorBrush.Color)");
Storyboard CellBackgroundChangeStory = new Storyboard();
Storyboard.SetTarget(colorChangeAnimation, BackGroundCellGrid);
Storyboard.SetTargetProperty(colorChangeAnimation, colorTargetPath);
CellBackgroundChangeStory.Children.Add(colorChangeAnimation);
CellBackgroundChangeStory.Begin();
// VariableColour & BaseColour are class of Color, timeSpan is Class of
// TimeSpan, BackGroundCellGrid is class of Grid;
// no need to create SolidColorBrush and binding to it in XAML;
// have fun!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With