绑定到DoubleAnimation.To

时间:2015-05-20 21:54:11

标签: wpf storyboard

我希望将DoubleAnimation.To绑定到依赖项属性,并在该属性更改时触发动画。我可以使基本动画工作,但无法弄清楚当属性发生变化时如何触发它。

该示例显示我尝试为Rectangle的Canvas.Left属性设置动画。请注意,我已将DoubleAnimation.To绑定到Position。我希望动画运行并在位置更改时移动我的矩形。有人能帮我找出正确的触发器吗?

<Viewbox>
<Canvas Height="200" Width="200">
    <Rectangle Name="MyRectangle" Canvas.Left="50" Canvas.Top="50" Width="100" Height="100" Fill="Blue">
        <Rectangle.Triggers>
            <EventTrigger RoutedEvent="Rectangle.Loaded">
                <BeginStoryboard>
                    <Storyboard Name="MyStoryboard">
                        <DoubleAnimation Storyboard.TargetName="MyRectangle" 
                                            Storyboard.TargetProperty="(Canvas.Left)"
                                            To="{Binding Position}" Duration="0:0:5" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Rectangle.Triggers>
    </Rectangle>
</Canvas>

1 个答案:

答案 0 :(得分:1)

答案是使用EventTrigger并将其RoutedEvent属性设置为Binding.TargetUpdated。此外,您必须将NotifyOnTargetUpdated = True添加到您的绑定(在我的情况下为Position)。

        <Viewbox>
        <Canvas Height="200" Width="200">
            <Rectangle Name="MyRectangle" Canvas.Left="50" Canvas.Top="50" Width="100" Height="100" Fill="Blue">
                <Rectangle.Triggers>
                    <EventTrigger RoutedEvent="Binding.TargetUpdated">
                        <BeginStoryboard>
                            <Storyboard Name="MyStoryboard">
                                <DoubleAnimation Storyboard.TargetName="MyRectangle" 
                                                    Storyboard.TargetProperty="(Canvas.Left)"
                                                    To="{Binding Position, NotifyOnTargetUpdated=True}" Duration="0:0:5" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Rectangle.Triggers>
            </Rectangle>
        </Canvas>
    </Viewbox>