我在.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();
}
总体来说,它看起来不错,并且可以完成我想做的所有事情,除了一个我无法处理的小细节-它在文本框的开头添加了一个空行,即:
有什么办法可以解决这个问题?
答案 0 :(得分:4)
在开头删除它
public MainWindow()
{
InitializeComponent();
logTextBox.Document.Blocks.Remove(logTextBox.Document.Blocks.FirstBlock);
}