WPF RichTextBox滚动条自动滚动实例、文本自动滚动实例
说明:
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); } }
运行结果: