How to get WPF ScrollViewer to automaticall scroll TextBlock content

DonBaechtel-7903 191 Reputation points
2023-04-01T14:03:45.84+00:00

In XAML I have a WPF TextBlock inside of a ScrollViewer.

I would like the ScrollViewer to automatically scroll the TextBlock contents so that newly entered text at the bottom of the TextBlock is always kept in view.

I am assuming the TextBlock Content will always get larger as I continue to append text to it.

The ScollViewr documentation is not clear on how to do this.

All Help is greatly appreciated.

<ScrollViewer VerticalScrollBarVisibility="Auto" 
                    Height="675" 
                    Width="344" 
                    HorizontalScrollBarVisibility="Disabled"
                    CanContentScroll="True">
                    <TextBlock x:Name="scriptText" 
                        Height="675" 
                        DockPanel.Dock="Top"
                        FontSize="14" 
                        TextWrapping="Wrap" 
                        Foreground="Black"
                        Padding="3"
                        Text=""/>
                </ScrollViewer>
Windows for business Windows Client for IT Pros User experience Other
Developer technologies XAML
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 44,751 Reputation points
    2023-04-03T12:33:44.3666667+00:00
    Hello there,
    
    Do you mean a TextBox, as opposed to a TextBlock? The default behavior for a TextBox is to show the most recent text as more text is entered.
    
    Window x:Class="textboxscrolltest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
            <TextBox Width="75" Height="25"/>
        </Grid>
    </Window>
    
    I don't think TextBlocks can scroll. You can put the TextBlock in a ScrollViewer.
    
    XAML:
    
    <ScrollViewer Name="MyScrollViewer">
        <TextBlock TextWrapping="Wrap">
            A bunch of text
        </TextBlock>
    </ScrollViewer>
    Code-behind:
    
    MyScrollViewer.ScrollToBottom();
    
    Hope this resolves your Query !!
    
    --If the reply is helpful, please Upvote and Accept it as an answer--
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.