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

来源:互联网 发布:天谕捏脸数据导入图 编辑:程序博客网 时间:2024/05/16 06:55

最近失眠睡不着,那就起来写博客吧。
在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();            }));        }    }}

效果如下:
这里写图片描述

0 0