說明:
1.后台代碼添加測試 數據
2.使用 richTextBox.ScrollToVerticalOffset()方法,滾動豎直方向滾動條位置
3.使用定時器DispatcherTimer,修改頁面顯示數據
4.自己計算處理,已經滾動的高度位置
Xaml代碼:
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="205*"/> <ColumnDefinition Width="87*"/> </Grid.ColumnDefinitions> <Button x:Name="button" Content="開始播放" HorizontalAlignment="Left" Margin="2,36,0,0" VerticalAlignment="Top" Width="75" Grid.Column="1" Height="29" Click="button_Click"/> <RichTextBox x:Name="richTextBox" HorizontalAlignment="Left" Height="209" Margin="10,36,0,0" VerticalAlignment="Top" Width="170"> </RichTextBox> </Grid>
后台添加測試數據代碼:
public text4() { InitializeComponent(); richTextBox.Document = doc; richTextBox.FontSize = 20; //添加內容 appendLine(null, "從你的全世界路過"); appendLine("one", "海上生明月"); appendLine(null, "從你的全世界路過"); appendLine(null, "天涯共此時"); appendLine("two", "張三豐"); appendLine(null, "從你的全世界路過"); appendLine(null, "魯迅先生"); appendLine(null,null); } FlowDocument doc = new FlowDocument(); private void appendLine(string name, string line) { Paragraph p = new Paragraph(); if (string.IsNullOrEmpty(name) == false) doc.RegisterName(name, p); Run r = new Run(line); p.TextAlignment = TextAlignment.Center; p.Inlines.Add(r); doc.Blocks.Add(p); }
定時器顯示控制代碼:
int pIndex = 0; double curTop = 0; private void button_Click(object sender, RoutedEventArgs e) { //定時控制內容顯示和滾動條位置 DispatcherTimer _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += (st, et) => { //獲取指定行的內容 BlockCollection col = richTextBox.Document.Blocks; int index = 0; TextElement prev = null; foreach (TextElement item in col) { //修改當前行的樣式 if (index == pIndex) { AlterStyle(item, prev); } index++; prev = item; } pIndex++; }; _timer.Start(); } private void AlterStyle(TextElement item, TextElement prev) { //當前行 Paragraph cP = item as Paragraph; cP.Foreground = Brushes.Red; TextRange range = new TextRange(cP.ContentStart, cP.ContentEnd); //滾動位置控制 if (pIndex > 0 && range.Text.Length > 0) { //上一行,樣式回調 if (prev != null) { prev.Foreground = Brushes.Black; } curTop += range.Text.Length > 7 ? 40 : 20; curTop += 20; richTextBox.ScrollToVerticalOffset(curTop); } }
運行結果: