user239390
user239390

Reputation:

How to make ScrollViewer automatic

I tried to place a TextBlock inside a ScrollViewer, and the scroll bar shows up correctly, but I cannot seem to make it automatically scroll down when the Text property of the TextBlock is updated. Here's the relevant part of the XAML:

<ScrollViewer>
  <TextBlock FontFamily="Consolas"
             Text="{Binding Current.Current.Discussion}"
             TextWrapping="Wrap" />
</ScrollViewer>

Help would be greatly appreciated, thanks!

Upvotes: 0

Views: 3296

Answers (2)

db42
db42

Reputation: 4544

Listen to the text changed event

    textBlock.TextChanged += (o, args) => ScrollTextBoxToBotton();

Actual function to scroll to bottom:

    private void ScrollTextBoxToBotton()
    {
        scrollViewer.UpdateLayout();
        scrollViewer.ScrollToVerticalOffset(double.MaxValue);
    }

Upvotes: 0

Gus
Gus

Reputation: 10659

By default, the behavior you get is that the scroll bars will adjust to the amount of text in the textblock, but the viewer will be showing the top of the text. To refresh that properly do this:

scrollViewer.UpdateLayout();
scrollViewer.ScrollToVerticalOffset(txtBlock.ActualHeight);

Upvotes: 4

Related Questions