Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color transition in WPF

I want to make a color transition of Background color of a WPF window.

How can I do this?

For example:

Brush i_color = Brushes.Red; //this is the initial color
Brush f_color = Brushes.Blue; //this is the final color

When I click on Button button1

private void button1_Click(object sender, RoutedEventArgs e)
{
    this.Background = f_color; //here the transition begins. I don't want to be quick. Maybe an interval of 4 seconds.
}
like image 312
Ionică Bizău Avatar asked Jul 23 '12 17:07

Ionică Bizău


1 Answers

In code it can be done with this

private void button1_Click(object sender, RoutedEventArgs e)
{
    ColorAnimation ca = new ColorAnimation(Colors.Red, Colors.Blue, new Duration(TimeSpan.FromSeconds(4)));
    Storyboard.SetTarget(ca, this);
    Storyboard.SetTargetProperty(ca, new PropertyPath("Background.Color"));

    Storyboard stb = new Storyboard();
    stb.Children.Add(ca);
    stb.Begin();
}

As H.B. pointed out this will work too

private void button1_Click(object sender, RoutedEventArgs e)
{
    ColorAnimation ca = new ColorAnimation(Colors.Blue, new Duration(TimeSpan.FromSeconds(4)));
    this.Background = new SolidColorBrush(Colors.Red);
    this.Background.BeginAnimation(SolidColorBrush.ColorProperty, ca);
}
like image 173
LPL Avatar answered Sep 23 '22 04:09

LPL