默認情況下,當更新WPF RichTextBox時,系統不會自動將更新的內容展示到可視範圍中,所以需要通過RichTextBox的一個方法ScrollToVerticalOffset來設置當前顯示的位置
但是ScrollToVerticalOffset方法的傳入參數是以像素爲單位的,看過許多文檔說通過讀取當前行的高度和行數以及顯示屏的分辨率來獲取行高,把我弄得頭大
不過最終還是找到了完美的解決方法,在此記錄一下
給富文本插入縱向的滾動條
ScrollViewer.VerticalScrollBarVisibility="Auto"
然後向RichTextBox添加內容,並將標題從當前位置動態移動到可視範圍的四分之一處
public void appendTitle(string content)
{
Paragraph paragraph = new Paragraph();
paragraph.FontFamily = new System.Windows.Media.FontFamily("微軟雅黑");
paragraph.FontSize = 16;
paragraph.FontWeight = FontWeights.Bold;
paragraph.LineHeight = 1;
paragraph.Background = Brushes.DarkCyan;
paragraph.Foreground = Brushes.LightCyan;
paragraph.Margin = new System.Windows.Thickness(0, 2, 0, 2);
paragraph.Padding = new Thickness(5, 5, 2, 5);
paragraph.IsEnabled = false;
//paragraph
paragraph.Inlines.Add(new Run(content));
this.richTextBox1.Document.Blocks.Add(paragraph);
//將標題動態移動到可視範圍
Paragraph selected = paragraph;
Rect rctStart = selected.ContentStart.GetCharacterRect(System.Windows.Documents.LogicalDirection.Forward);
Rect rctEnd = selected.ContentEnd.GetCharacterRect(System.Windows.Documents.LogicalDirection.Forward);
double orignLineHeight = richTextBox1.VerticalOffset;
double endLineHeight = (rctStart.Top + rctEnd.Bottom) / 2 + richTextBox1.VerticalOffset - richTextBox1.ViewportHeight / 4;
int index = 0,number=10;
DispatcherTimer _timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromSeconds(0.01);
_timer.Tick += (st, et) =>
{
richTextBox1.ScrollToVerticalOffset((endLineHeight - orignLineHeight) * (index / (double)number) + orignLineHeight);//
if (index++ > number)
{
_timer.Stop();
}
};
_timer.Start();
}
看下效果