简体   繁体   中英

How to animate an image in WPF with a mousedown event on the canvas or window

I have a window with a canvas using WPF and C#. On the canvas I have an image. I want to apply a mousedown event to the window or canvas that will animate the image left or right depending upon which mouse button is clicked. Left mouse button should move the image left and right mouse button should move the image to the right. The movement should stop when the button is no longer down. I have done this in winforms using a timer, but Im just starting to work with WPF and I cant seem to find any examples of mouse triggered animation. Can anyone help out a WPF newbie?

This is usually done by starting Storyboards on EventTriggers:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM