wpfscaledoubleanimation

wpf FrameworkElement.width Animation


I put my rectangle on the Canvas at the wpf. We gave doubleAnimation using "FrameworkElement.With" to this rectangle. If you try to change the rectangle width after completing the animation, it does not change. Can you guess why?


Solution

  • The animation will change and keep the value with a higher priority, so your normal set value will not work. You can read Microsoft docs for more details about the Dependency Property Value Precedence.

    You have two different methods to change your animated property value.

    1st. Don't assign the animation To property

    If you create your animation in this way below, you need to remove the To property.

    <DoubleAnimation Storyboard.TargetName="element" Storyboard.TargetProperty="Width"
                     From="0" To="100" Duration="0:0:1" />
    

    Remove To.

    <DoubleAnimation Storyboard.TargetName="element" Storyboard.TargetProperty="Width"
                     From="0" Duration="0:0:1" />
    

    When you're trying to begin the animation, call like this:

    storyboard.Begin();
    element.Width = 100;
    

    In this way, your storyboard will begin and then animated your Width to your last set value.

    2nd. Remove the animation from your Width property

    Every time your storyboard or animation completed, begin another null animation to remove the higher priority value of Width property.

    element.BeginAnimation(WidthProperty, null);