#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 software development and sailing.

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

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

Leave a comment