WPF富文本日志

        public void AddFormLog(string msg, System.Windows.Media.Brush color)
        {
            _ = Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate ()
            {
                string t = GlobalConst.CurrentDate;// string.Format("{0:G}", DateTime.Now);
                Run run = new Run();
                run.Text = t + " 信息:" + msg;
                run.Foreground = color;

                Paragraph paragraph = new Paragraph(run)
                {
                    LineHeight = 2,
                };
                //rtxtLog.Document.Blocks.InsertAfter(); ;
                //插入到最前面
                rtxtLog.Document.Blocks.InsertBefore(rtxtLog.Document.Blocks.FirstBlock, paragraph);
               //也可以插入到最后面
                //rtxtLog.Document.Blocks.Add(paragraph);

                // 滚动至最后行
                //rtxtLog.ScrollToEnd();
                rtxtLog.ScrollToHome();
                // 删除
                if (rtxtLog.Document.Blocks.Count > 1000)
                {
                    for (int i = 1000; i < rtxtLog.Document.Blocks.Count; i++)
                    {
                        _ = rtxtLog.Document.Blocks.Remove(rtxtLog.Document.Blocks.FirstBlock);
                    }
                }
            });
        }

xaml文件 

        <Grid Grid.Row="2" Grid.ColumnSpan="2">
          
            <RichTextBox  Name="rtxtLog" Background="Black" Foreground="Lime" AutomationProperties.IsRowHeader="True">
                <FlowDocument>
                    <Paragraph  >
                        <!--<Run Text="log" Foreground="Red"/>
                        <LineBreak></LineBreak>
                        <Run Text="log1" Foreground="Lime"/>-->
                    </Paragraph>
                </FlowDocument>
            </RichTextBox>
        </Grid>

猜你喜欢

转载自blog.csdn.net/easyboot/article/details/132046626
今日推荐