Akash
Akash

Reputation: 1726

Take an action on first or last click of repeatButton

How can I specify an action on the first or last click of a RepeatButton?

Example:

A label is initially set to 0

While RepeatButtonis pressed, value is incremented continuously

When RepeatButtonis left, the value resets to 0

alternatively, set the counter to 0 immediately when the button is pressed, and start incrementing

Upvotes: 1

Views: 153

Answers (1)

Sheridan
Sheridan

Reputation: 69985

You wouldn't need to use a RepeatButton to do what you want. Instead, it would be better to use a standard Button and to handle the PreviewMouseDown and PreviewMouseUp events. Try something like this:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Button Content="Press and Hold" PreviewMouseDown="Button_PreviewMouseDown" 
        PreviewMouseUp="Button_PreviewMouseUp" />
    <TextBlock Grid.Column="1" Text="{Binding YourValue}" />
</Grid>

...

private DispatcherTimer timer = new DispatcherTimer();

private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    timer.Interval = TimeSpan.FromMilliseconds(100);
    timer.Tick += Timer_Tick;
    timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
    YourValue++;
}

private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
    timer.Stop();
}

You can adjust the number of milliseconds between the value increments to suit your requirements.

Upvotes: 1

Related Questions