5

Our application starts several background processes and put their output into TextBoxes - each in a separate TabItem in a TabControl. I want the TextBoxes to automatically scroll to show the last output line, so in the data handling function that adds the output/error line to the text box, I also call TextBox.ScrollToEnd():

void OnServerProcessOutputDataReceived(object sender, DataReceivedEventArgs e)
{
    if (e.Data != null)
    {
        Dispatcher.Invoke(new Action(() =>
            {
                TextBox tb = getServerProcessOutputTextBox(sender);
                if (tb != null)
                {
                    tb.AppendText(e.Data + Environment.NewLine);
                    tb.ScrollToEnd();
                }
            }));
    }
}

This works great for the TextBox in the active tab, but when I switch to another tab, I see that it wasn't scrolled down to the end.

Is this a known problem? Is there a way to fix it?

wonea
  • 4,783
  • 17
  • 86
  • 139
splintor
  • 9,924
  • 6
  • 74
  • 89
  • Here is an answer for how to do this: http://stackoverflow.com/questions/4055720/scrolling-to-the-end-of-a-single-line-wpf-textbox – Tal Segal Jul 07 '13 at 13:51

2 Answers2

16

Set the CaretIndex:

   if (tb != null) 
   { 
       tb.AppendText(e.Data + Environment.NewLine); 
       tb.CaretIndex = tb.Text.Length;
       tb.ScrollToEnd(); 
   } 
Reydon Ace
  • 176
  • 1
  • 3
  • 5
    This solution wouldn't work for me unless the TextBox had focus: tb.Focus(). – Fueled Jan 09 '12 at 14:34
  • This 10 yr old bug still persists. If you programmatically move the focus away after this, then it will still not do it. – A. Vieira Nov 26 '20 at 10:51
0

Looks like a bug... you should report it on Microsoft Connect

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758