#851 – Using RepeatButtons to Move Something

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;
        }
    }

851-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: