#851 – Using RepeatButtons to Move Something
June 27, 2013 Leave a comment
The RepeatButton functions like a regular Button, but continuously fires Click events while the button remains depressed.
One possible use for a RepeatButton is to move something while the user holds the mouse button down.
Below, we use a pair of RepeatButtons to move a picture around a Canvas.
<Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Canvas Grid.ColumnSpan="2"> <Image Source="Augustus.jpg" Height="100" Canvas.Left="{Binding PictureLeft}" Canvas.Top="20"/> </Canvas> <RepeatButton Grid.Row="1" Content="Left" Padding="10,5" Margin="5" HorizontalAlignment="Center" Click="rptLeft_Click"/> <RepeatButton Grid.Row="1" Grid.Column="1" Content="Right" Padding="10,5" Margin="5" HorizontalAlignment="Center" Click="rptRight_Click"/> </Grid>
public partial class MainWindow : Window, INotifyPropertyChanged { public MainWindow() { this.InitializeComponent(); this.DataContext = this; } public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void RaisePropertyChanged(string propName) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } private int pictureLeft = 0; public int PictureLeft { get { return pictureLeft; } protected set { pictureLeft = value; RaisePropertyChanged("PictureLeft"); } } private void rptLeft_Click(object sender, RoutedEventArgs e) { PictureLeft -= 5; } private void rptRight_Click(object sender, RoutedEventArgs e) { PictureLeft += 5; } }