首页 > 解决方案 > 如何删除 RichTextBox 的第一个空行?

问题描述

我在 .xaml 文件中有一个这样定义的 RichTextBox:

<RichTextBox x:Name="logTextBox" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Auto" IsReadOnly="True" FontSize="14"  Margin="48,10,49,9" Background="Black">
            <RichTextBox.Resources>
                <Style TargetType="{x:Type Paragraph}">
                    <Setter Property="Margin" Value="0"/>
                </Style>
                <Style TargetType="ScrollViewer">
                    <Setter Property="MaxWidth" Value="500" />
                </Style>
            </RichTextBox.Resources>
        </RichTextBox>

我正在像这样使用它:

    public void AddLog(string log, Color color)
    {
        Run run = new Run(log);
        run.Foreground = new SolidColorBrush(color);
        Paragraph paragraph = new Paragraph(run);
        var numberOfBlocks = logTextBox.Document.Blocks.Count;
        const int MaxNumberOfBlocks = 100;
        if(numberOfBlocks > MaxNumberOfBlocks)
        {
            logTextBox.Document.Blocks.Remove(logTextBox.Document.Blocks.FirstBlock);
        }
        logTextBox.Document.Blocks.Add(paragraph);
        logTextBox.ScrollToEnd();
    }

总的来说,它看起来不错,可以做我想做的所有事情,除了一个我无法处理的小细节 - 它在文本框的开头添加了一个空行,即:

在此处输入图像描述

有没有什么办法解决这一问题?

标签: c#wpf

解决方案


一开始就去掉

 public MainWindow()
 {
    InitializeComponent();                
    logTextBox.Document.Blocks.Remove(logTextBox.Document.Blocks.FirstBlock);
 }

推荐阅读