Question

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?

Was it helpful?

Solution

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top