How to make WPF TextBox with a scrollbar automatically scroll to the bottom when lines are added?

You can whenever you add content to that TextBox or when you listen to the event TextChanged fire this method: TextBoxBase.ScrollToEnd().


You could write an attached property or even better a behavior that listens to the TextChanged event and scrolls to the bottom in the callback.


Visual Studio output window behavior is special, because it will only keep auto scrolling down if the caret is at the end of the text box, which allows you to examine the output without being disturbed if new lines are added to it.

I've got such behavior with this code

bool scrollToEnd = TbEvents.CaretIndex == TbEvents.Text.Length;
TbEvents.AppendText(text + Environment.NewLine);
if (scrollToEnd)
{
    TbEvents.CaretIndex = TbEvents.Text.Length;
    TbEvents.ScrollToEnd();
}

Tags:

.Net

Wpf

Scroll