#931 – Scrolling Text in a TextBox from Code

If you want to programmatically scroll the text within a TextBox control, you can use any of the scrolling methods available to a ScrollViewer.  Specifically:

  • Methods for scrolling vertically
    • LineUp / LineDown
    • PageUp / PageDown
    • ScrollToHome / ScrollToEnd
  • Methods for scrolling horizontally
    • LineLeft / LineRight
    • PageLeft / PageRight
    • ScrollToLeftEnd / ScrollToRightEnd

These methods scroll content as if the user had clicked on the corresponding scrollbar–either on the arrows at the end (single line) or in the empty space (single page).

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <StackPanel>
            <Button Content="PageUp" Click="btnPageUp_Click"/>
            <Button Content="LineUp" Click="btnLineUp_Click"/>
            <Button Content="LineDown" Click="btnLineDown_Click"/>
            <Button Content="PageDown" Click="btnPageDown_Click"/>
        </StackPanel>
        <TextBox Name="txtMain" Grid.Column="1" Margin="5"
                 Text="{Binding SomeText}"
                 TextWrapping="NoWrap"
                 AcceptsReturn="True"
                 VerticalScrollBarVisibility="Auto"
                 HorizontalScrollBarVisibility="Auto"/>
        <StackPanel Orientation="Horizontal" Grid.Row="1" Grid.Column="1">
            <Button Content="PageLeft"  Click="btnPageLeft_Click"/>
            <Button Content="LineLeft" Click="btnLineLeft_Click"/>
            <Button Content="LineRight" Click="btnLineRight_Click"/>
            <Button Content="PageRight" Click="btnPageRight_Click"/>
        </StackPanel>
    </Grid>

Event handlers would follow the form:

        private void btnPageUp_Click(object sender, RoutedEventArgs e)
        {
            txtMain.PageUp();
        }

931-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.

One Response to #931 – Scrolling Text in a TextBox from Code

  1. Pingback: Dew Drop – October 18, 2013 (#1,648) | Morning Dew

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: