Recently, I’ve been playing with the WPF `RepeatButton`. I’ve not used it before, as it does seem to fulfil a very specific purpose. The use that I was trying to put it to was to act in the same way as you would expect your alarm clock to behave if you changed the time.
Say it’s currently 3:10 and you need it to be 3:15; you’d simply press the plus button five times, right? But what if you want it to be 17:50? Well, you’d hold the plus button down, but you wouldn’t expect it to increase by minutes; you’d maybe expect it to jump by 30 mins at a time after holding the plus button for a while.
The RepeatButton can do the same⦠but unfortunately not out of the box.
The Box
What you can do out of the box is this:
<RepeatButton Content="+" Name="IncreaseButton"/>
And to handle the click:
IncreaseButton.Click += new RoutedEventHandler(IncreaseButton_Click);
Finally:
private void IncreaseButton_Click(object sender, RoutedEventArgs e) { Value += 1; }
What’s wrong with that?
So far, so good, but what if I want the increment to increase though, as described in the alarm clock scenario above? I have two options here. One thing you can do is to increase the frequency that you increment; however, what I wanted to do was to increase the increment. The way I did it was to store a count:
private int _incrementButtonRepeat;
Then, in the `click` event:
private void IncreaseButton_Click(object sender, RoutedEventArgs e) { if (_incrementButtonRepeat > 5) Value += 5; else Value += 1; _incrementButtonRepeat++; }
Finally, you’ll need to reset:
private void IncreaseButton_PreviewMouseUp(object sender, MouseButtonEventArgs e) { _incrementButtonRepeat = 0; }
A little gotcha here is the MouseUp command never seems to fire, because it’s apparently handled internally. Use the preview to intercept it first.
Conclusion
You could create a very basic control that encapsulates this behaviour, based on some parameters; then you’d never have to consider this again.