How to change EasingDoubleKeyFrame value at Runtime?

社会主义新天地 提交于 2019-12-10 23:39:53

问题


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...



来源:https://stackoverflow.com/questions/10425654/how-to-change-easingdoublekeyframe-value-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!