Search code examples
windows-runtimewinrt-xamlwinrt-async

Better way of logic loop while button is pressed?


So I have a button on a WinRT UserControl that I want to increase or decrease a integer value (CurrentValue) while you hold down the button.

I ended up with this implementation below, which works but does not look to good or is it okay?

I searched for an event to use but I got stuck using click and setting the button.clickmode to press.

I use the bool _increasePushed to track if already pushed in so I don't get multiple event triggers.

    private bool _increasePushed;
    private const int PushDelay = 200;

    private async void ButtonIncreaseClick(object sender, RoutedEventArgs e)
    {
        var button = sender as Button;
        if (button == null) return;

        if (_increasePushed)
        {
            return;
        }

        _increasePushed = true;

        while (button.IsPressed)
        {
            CurrentValue++;
            await Task.Delay(PushDelay);
        }

        _increasePushed = false;
    }

XAML on UserControl

    <Button x:Name="buttonIncrease" Content="Bla bla"
            Click="ButtonIncreaseClick" ClickMode="Press" />

Solution

  • The better way would be to use a RepeatButton which does exactly what you are trying to replicate. It has a Delay property to wait for the first repeated click as well as an Interval property that controls how often the Click event is raised.