如何使用画布或窗口上的mousedown事件为WPF中的图像设置动画

时间:2012-11-14 22:01:25

标签: c# wpf image mouseevent animated

我有一个使用WPF和C#的画布窗口。在画布上我有一个图像。我想将一个mousedown事件应用于窗口或画布,它将根据单击的鼠标按钮向左或向右移动图像。鼠标左键应该移动图像左右鼠标按钮应该将图像向右移动。当按钮不再向下时,移动应该停止。我使用计时器在winforms中完成了这个,但我刚刚开始使用WPF,我似乎无法找到任何鼠标触发动画的例子。任何人都可以帮助WPF新手吗?

1 个答案:

答案 0 :(得分:1)

这通常是通过在EventTriggers上启动Storyboard来完成的:

<Canvas Background="White">
    <Canvas.Resources>
        <Storyboard x:Key="MoveLeft" TargetName="imageView" TargetProperty="(Canvas.Left)">
            <DoubleAnimation To="50" Duration="0:0:0.25"/>
        </Storyboard>
        <Storyboard x:Key="MoveRight" TargetName="imageView" TargetProperty="(Canvas.Left)">
            <DoubleAnimation To="250" Duration="0:0:0.25"/>
        </Storyboard>
        <Storyboard x:Key="Restore" TargetName="imageView" TargetProperty="(Canvas.Left)">
            <DoubleAnimation To="150" Duration="0:0:0.25"/>
        </Storyboard>
    </Canvas.Resources>

    <Canvas.Triggers>
        <EventTrigger RoutedEvent="Image.MouseLeftButtonDown">
            <BeginStoryboard Storyboard="{StaticResource MoveLeft}"/>
        </EventTrigger>
        <EventTrigger RoutedEvent="Image.MouseRightButtonDown">
            <BeginStoryboard Storyboard="{StaticResource MoveRight}"/>
        </EventTrigger>
        <EventTrigger RoutedEvent="Image.MouseRightButtonUp">
            <BeginStoryboard Storyboard="{StaticResource Restore}"/>
        </EventTrigger>
        <EventTrigger RoutedEvent="Image.MouseLeftButtonUp">
            <BeginStoryboard Storyboard="{StaticResource Restore}"/>
        </EventTrigger>
    </Canvas.Triggers>

    <Image Width="200" Canvas.Left="150" Canvas.Top="90" x:Name="imageView" Source="floppydisk.jpg"/>
</Canvas>