Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

wpf - Multiline Textbox with automatic vertical scroll

There are a lot of similiar questions over internet, on SO included, but proposed solutions doesn't work in my case. Scenario : there is a log textbox in xaml

 <TextBox Name="Status"
          Margin="5"
          Grid.Column="1"
          Grid.Row="5"
          HorizontalAlignment="Left"
          VerticalAlignment="Top"
          Width="600"
          Height="310"/>

There are methods in code-behind that do some work and add some multiline (maybe that's the problem?) messages into this textbox:

private static void DoSomeThings(TextBox textBox)
{
   // do work
   textBox.AppendText("Work finished
"); // better way than Text += according to msdn
   // do more
   textBox.AppendText("One more message
");
   ...
}

private static void DoSomething2(TextBox textBox)
{
   // same as first method
}

Need to scroll to bottom of textbox after all actions take place. Tried ScrollToEnd(), ScrollToLine, wrapping textbox into ScrollViewer, Selection and Caret workarounds, attaching ScrollToEnd to TextChanged. None of this works, after execution lines that overflow textbox height still need to be scrolled to manually. Sorry for duplicate question, i guess i'm missing some minor issues that can be resolved quickly by someone that has fresh vision on the problem. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to this question: TextBox.ScrollToEnd doesn't work when the TextBox is in a non-active tab

You have to focus the text box, update the caret position and then scroll to end:

Status.Focus();
Status.CaretIndex = Status.Text.Length;
Status.ScrollToEnd();

EDIT

Example TextBox:

<TextBox TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" 
         AcceptsReturn="True" Name="textBox"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...