WPF动画位置取决于窗口大小

时间:2017-09-28 08:52:26

标签: c# wpf animation

我想创建一个动画(如果可能的话,来自xaml),其中一个Rectangle对象从页面外部(右侧)滑动并且贴合它。

动画应该可以在任何大小的窗口上运行,因此我创建它是这样的:

<Storyboard x:Key="SlidingIntro">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="icon">
        <EasingDoubleKeyFrame KeyTime="0" Value="{Binding ActualWidth, ElementName=AnimationCanvas}"/>
        <EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>
<Page.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
        <BeginStoryboard Storyboard="{StaticResource SlidingIntro}"/>
    </EventTrigger>
</Page.Triggers>

将Rectangle初始化为:

<Canvas x:Name="AnimationCanvas">
        <Rectangle Width="{Binding ActualWidth, ElementName=AnimationCanvas}" 
                       Height="{Binding ActualHeight, ElementName=AnimationCanvas}" 
                       Canvas.Top="{Binding ActualHeight, ElementName=AnimationCanvas, Converter={StaticResource Math}, ConverterParameter=-x/2}"
                       RenderTransformOrigin="0.5,0.5" >
            <Rectangle.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform/>
                    <TranslateTransform X="{Binding ActualWidth, ElementName=AnimationCanvas}"/>
                </TransformGroup>
            </Rectangle.RenderTransform>
        </Rectangle>
    </Canvas>

事情就是矩形出现在它的最终位置而没有动画。它就像第一帧的值是0,因为绑定失败了......有什么关于它的冻结?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

<Grid>
    <Rectangle Fill="Gray">
        <Rectangle.Style>
            <Style TargetType="Rectangle">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="Loaded">
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation To="0" Duration="0:0:1"
                                    Storyboard.TargetProperty="RenderTransform.X"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>
        <Rectangle.RenderTransform>
            <TranslateTransform X="{Binding ActualWidth,
                                RelativeSource={RelativeSource AncestorType=Rectangle}}"/>
        </Rectangle.RenderTransform>
    </Rectangle>
</Grid>