Tuesday, December 27, 2011

WPF – Repeat Button


WPF Repeat button is similar to normal button but it gives you control how and when button's click event will get fired. Repeat button allows you to repeatedly fire click event starting from pressed until it is released. The repeated behavior defines by Delay and Interval properties of repeat button. The delay property defines time to start click event and the Interval property controls the time to repeat click event.

Repeat button continuously fires click event when it is pressed and held. The below example demonstrates two repeat buttons add and remove. On press and hold of add button counter value increase and decrease on press and hold of remove button.

XAML

<Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition />
    <ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition />
</Grid.RowDefinitions>
<RepeatButton Width="100" Height="40"
                Name="btnAdd"
                Content="Add"
                Grid.Column="0" Grid.Row="0"
                Interval="100" Delay="1000"
                Click="btnAdd_Click" />
<RepeatButton Width="100" Height="40"
                Name="btnRemove"
                Content="Remove"
                Grid.Column="1" Grid.Row="0"
                Interval="100" Delay="1000"
                Click="btnRemove_Click" />
<TextBlock Height="50" Width="50"
            Name="txtDisplay"
            Grid.Row="1" Grid.ColumnSpan="2"
            TextAlignment="Center"
            FontWeight="Bold"
            FontSize="35"
            Foreground="Red" />
</Grid>

Code

public partial class RepeatButtonDemo : Window
{
    public int counter;
    public RepeatButtonDemo()
    {
        InitializeComponent();
    }

    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        txtDisplay.Text = (++counter).ToString();
    }

    private void btnRemove_Click(object sender, RoutedEventArgs e)
    {
        txtDisplay.Text = (--counter).ToString();
    }
}

Output




As per above code, when mouse button pressed and hold on add button, the label (in red text) value increases as per delay and interval specified on add repeat button. The reverse thing happens when mouse button is pressed and hold on remove button.

See Also – 

No comments:

Post a Comment