WPF中RichTextBox实现和Winform一样的效果

    xiaoxiao2025-07-09  3

    最近失眠睡不着,那就起来写博客吧。 在winform中我们经常使用richtextbox来记录程序日志,能够不同的追加显示不同的颜色,并且随着追加滑动条自动滚动。那么在WPF中如何实现呢?同样,也可以使用Richtextbox来实现,代码如下:首先在MainWindow.xaml中加入一个RichTextBox:

    <RichTextBox Name="rb" Margin="0,0,0,00" Grid.Row="1" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto"></RichTextBox>

    主要要设置ScrollViewer.VerticalScrollBarVisibility=”Auto”否则看不到滚动条 我们再代码中,利用线程更新UI,并将信息输出到Richtextbox:

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TextBlock { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btn_Click(object sender, RoutedEventArgs e) { new System.Threading.Thread(() => { for (int i = 0; i < 100; i++) { Color color = i % 2 == 0 ? Colors.Red : Colors.Blue; UpdateText("this is i:" + i.ToString(), color, true); System.Threading.Thread.Sleep(500); } }).Start(); } delegate void deleUpdate(string msg, Color color, bool nextline); public void UpdateText(string msg, Color color, bool nextline) { this.Dispatcher.Invoke(new Action(() => { SolidColorBrush _brushColor = new SolidColorBrush(color); string _msg=nextline ? msg + "\r\n" : msg; var r = new Run(_msg); Paragraph p = new Paragraph() { Foreground = _brushColor }; p.Inlines.Add(r); rb.Document.Blocks.Add(p); rb.Focus(); rb.ScrollToEnd(); })); } } }

    效果如下:

    转载请注明原文地址: https://ju.6miu.com/read-1300521.html
    最新回复(0)