WPF: Use the C # code to make coloranimation animated for the brush.

Source: Internet
Author: User

Animation adding is generally in XAML, but at some point in time it is necessary to dynamically use C # To write the animation logic.

 

Use storyboard. Begin

The first method is relatively simple. For example, a rectangle has been defined in XAML:

<Rectangle name = "rectangle"/>

 

We change the rectangle color from red to green:

VaR storyboard = new storyboard ();

Storyboard. settarget (storyboard, rectangle );

Storyboard. settargetproperty (storyboard, new propertypath ("fill. Color "));

 

VaR coloranm = new coloranimation (colors. Red, new duration (timespan. fromseconds (1 )));

Coloranm. From = colors. Green;

Storyboard. Children. Add (coloranm );

 

Storyboard. Begin ();

Note that the settargetproperty of storyboard requires a propertypath object. Here, the propertypath is used to specify the color attribute of the fill attribute.

 

Use animatable. beginanimation

If you use animatable. beginanimation directly, you can only use the solidinanimation method of solidcolorbrush. Because the control freezable. isfrozen directly defined on XAML is true. Therefore, we can only manually create the object to be animated, set our own solidcolorbrush that is not frozen (freezable. isfrozen = false), and use the solidinanimation of this solidcolorbrush to start the animation.

 

Code:

VaR solid = new solidcolorbrush (colors. Green );

// Create a rectangle

VaR rec = new rectangle () {fill = solid };

// Add a rectangle to the interface

Grid. Children. Clear ();

Grid. Children. Add (REC );

 

VaR coloranm = new coloranimation (colors. Red, new duration (timespan. fromseconds (1 )));

Coloranm. From = colors. Green;

 

Solid. beginanimation (solidcolorbrush. colorproperty, coloranm );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.