Chris Lees
Chris Lees

Reputation: 2210

Start Animation While Button IsPressed in WPF

I have this DoubleAnimation in my XAML that scrolls a ScrollViewer up and down depending on a button which is pressed. I'm trying to switch it to animate (scroll) indefinitely when the button is pressed and stop animating when the button is released. I cant seem to figure out how to do this in XAML. I'd like to avoid doing this in code because I'm using an MVVM pattern and have been pretty good about separating the UI from the logic. Here's my animation code

<UserControl.Triggers>
    <EventTrigger RoutedEvent="Button.Click" SourceName="ScrollUp">
        <BeginStoryboard HandoffBehavior="Compose">
            <Storyboard Duration="0:0:1">
                <DoubleAnimation 
                    Storyboard.TargetName="ScrollViewerView"
                    Storyboard.TargetProperty="(wpf:ScrollViewerBinding.VerticalOffset)" 
                    To="{Binding NewVerticalScrollPositionUp}">
                    <DoubleAnimation.EasingFunction>
                        <SineEase EasingMode="EaseInOut"/>
                    </DoubleAnimation.EasingFunction>
                </DoubleAnimation>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
    <EventTrigger RoutedEvent="Button.Click" SourceName="ScrollDown">
        <BeginStoryboard HandoffBehavior="Compose">
            <Storyboard Duration="0:0:0:1">
                <DoubleAnimation 
                    Storyboard.TargetName="ScrollViewerView"
                    Storyboard.TargetProperty="(wpf:ScrollViewerBinding.VerticalOffset)" 
                    To="{Binding NewVerticalScrollPositionDown}">
                    <DoubleAnimation.EasingFunction>
                        <QuadraticEase EasingMode="EaseInOut"/>
                    </DoubleAnimation.EasingFunction>
                </DoubleAnimation>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</UserControl.Triggers>

When I press the down button, it animates, scrolling the ScrollViewer down. The same goes for when I press the up button. But I cant figure out a way to make the animation keep going while the button is down.

Upvotes: 0

Views: 1367

Answers (2)

Mike Strobel
Mike Strobel

Reputation: 25623

Use a RepeatButton instead of a regular Button. A RepeatButton functions like the arrow buttons on a ScrollBar and continues to fire at a fixed interval for as long as it is pressed. Note that its Interval property is measured in milliseconds.

Upvotes: 1

ΩmegaMan
ΩmegaMan

Reputation: 31616

Create a new animation which runs continuously and start it on the button press. Then stop the continuous animation on the button release.

Upvotes: 0

Related Questions