WPF Repeat Button


The RepeatButton acts like a Button except that it continuously raises the Click event as long as the button is being pressed. In our example, we are just using the Click event to add or subtract from a number. We need to convert the string to a number, add or subtract and then convert it back to a string.

<Window x:Class="RepeatButton.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:RepeatButton"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="RepeatButton" Height="150" Width="200">
    <StackPanel>
        <RepeatButton Name="AddBtn" Click="AddBtn_Click">Add 1</RepeatButton>
        <RepeatButton Name="SubtractBtn" Click="SubtractBtn_Click">Subtract 1</RepeatButton>
        <Label Name="lbl">1</Label>
    </StackPanel>
</Window>

Below is the C# code.

using System;
using System.Windows;
namespace RepeatButton
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            int num = Convert.ToInt32(lbl.Content);
            num++;
            lbl.Content = num.ToString();
        }
        private void SubtractBtn_Click(object sender, RoutedEventArgs e)
        {
            int num = Convert.ToInt32(lbl.Content);
            num--;
            lbl.Content = num.ToString();
        }
    }
}