How to change EasingDoubleKeyFrame value at Runtim

2019-07-21 10:59发布

问题:

I am trying to make a TranslateTransform animation. In the animation, I need my object to remain at the center of the window. I know WPF animation is Freezable. I am using a converter, but it initializes values at startup. Is there any way to set the value of EasingDoubleKeyFrame at runtime?

Here is my XAML code:

<Storyboard x:Key="Storyboard1">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="grid">
        <EasingDoubleKeyFrame KeyTime="0" Value="{Binding Width, Converter={StaticResource Minus}, ElementName=grid}"/>
        <EasingDoubleKeyFrame KeyTime="0:0:1" Value="{Binding Width, Converter={StaticResource EnteringValueConverter}, ElementName=grid}"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

回答1:

Add an x:Name Attribute to the EasingDoubleKeyFrame Element. Afterwards you should be able to access it via code:

x:Name="keyframe"

Then:

keyframe.SetValue(EasingDoubleKeyFrame.ValueProperty, yourValue);



回答2:

"This is because Animations are freezable objects. There is more information in the MSDN Documentation, but basically it means you can't use binding because properties in the frozen object (i.e. the animation) cannot change.

To get around this limitation, you will need to do some or all of the work in code-behind."

quote from Stackoverflow



回答3:

the EasingDoubleKeyFrame cannot be accessed via x:Name attribute. Instead you should use a different approach to define the EasingDoubleKeyFrame as StaticResource and link it via ResourceKey like this:

<UserControl.Resources>
    <EasingDoubleKeyFrame x:Key="myEasingKey" KeyTime="0:0:2" Value="136" />
    <Storyboard x:Key="Storyboard1">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
                                       Storyboard.TargetName="rectangle">
             <StaticResource ResourceKey="myEasingKey" />
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
</UserControl.Resources>

Access the it via code behind like below:

(EasingDoubleKeyFrame)Resources["myEasingKey"].Value = X;

Hope this helps...