WPF TextBox自动滚动到最户一行

时间:2022-09-28 16:58:14

textBox经常用来显示程序的运行状态或者消息,如何让他自动滚动呢?

在显示消息代码下加一条自动滚动到底部的语句即可:

TextBox1.ScrollToEnd();

(如果要显示垂直滚动条设置VerticalScrollBarVisibility="Auto",如果不显示设置为Hidden)

我用的程序代码如下:

this.Dispatcher.Invoke(new Action(() =>
{
//大于100行清除记录,可选
if (txtReceived.LineCount > 100)
{
txtReceived.Clear();
}
txtReceived.AppendText(string.Format("当前时间{0:HH:MM:ss}\n", DateTime.Now));
//自动滚动到底部
txtReceived.ScrollToEnd();
}));