我正在開發一個 WPF 應用程式,我需要一個空間以類似于控制臺的方式頻繁顯示彩色文本行(新行顯示在底部,其余部分向上移動)。我決定使用為此目的RichTextBox命名的控制元件:outputBox
<RichTextBox Name="outputBox"
Grid.Row="0"
Background="Black"
Foreground="White"
Margin="10"
FontSize="14"
IsReadOnly ="True"
Focusable="False"
FontFamily="Consolas"
VerticalScrollBarVisibility="Visible"
>
我還創建了以下方法來將新的文本行(每個不同的顏色)附加到outputBox:
private void PrintMessage(string msg, MessageType type = MessageType.Default)
{
TextRange tr = new(this.Window.outputBox.Document.ContentEnd, this.Window.outputBox.Document.ContentEnd);
tr.Text = "\n" msg;
switch (type)
{
case (MessageType.Default):
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.LightGray);
break;
case (MessageType.UserInput):
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Aqua);
break;
case (MessageType.SystemFeedback):
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.DarkSalmon);
break;
}
Window.outputBox.ScrollToEnd();
}
問題是,當outputBox達到大量文本行(例如 100 000)時,應用程式的性能會顯著下降。為了解決這個問題,我想在 上設定文本行的限制outputBox,因此當達到該限制時,第一行將被洗掉/清除,而不會丟失剩余文本行的文本格式。
如何做到這一點?
uj5u.com熱心網友回復:
如果將 RichTextBox 的文本添加Inlines到Paragraph.
但是為了在縮小檔案以限制其中的某些行數時提高性能,我建議限制段落大小。
下面的代碼實作了這個邏輯:
public static class RichTextBoxExt
{
public static void PrintMessage(this RichTextBox rtb, string msg, MessageType type = MessageType.Default)
{
// Maximum of blocks in the document
int MaxBlocks = 500;
// Maximum of lines in one block (paragraph)
int InlinesPerBlock = 500;
SolidColorBrush brush = Brushes.LightGray;
switch (type)
{
case MessageType.UserInput:
brush = Brushes.Aqua;
break;
case MessageType.SystemFeedback:
brush = Brushes.DarkSalmon;
break;
}
// Get the latest block in the document and try to append a new message to it
if (rtb.Document.Blocks.LastBlock is Paragraph paragraph)
{
var nl = Environment.NewLine;
// If the current block already contains the maximum count of lines create a new paragraph
if (paragraph.Inlines.Count >= InlinesPerBlock)
{
nl = string.Empty;
paragraph = new Paragraph();
rtb.Document.Blocks.Add(paragraph);
}
paragraph.Inlines.Add(new Run(nl msg) { Foreground = brush });
}
if (rtb.Document.Blocks.Count >= MaxBlocks)
{
// When the number of lines more that (MaxBlocks-1)*InlinesPerBlock remove the first block in the document
rtb.Document.Blocks.Remove(rtb.Document.Blocks.FirstBlock);
}
}
}
也許Margin應該調整段落以獲得更好的視覺效果:
<RichTextBox x:Name="rtb" Margin="3" VerticalScrollBarVisibility="Auto">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="2,0,0,2"/>
</Style>
</RichTextBox.Resources>
<FlowDocument>
<Paragraph>
</Paragraph>
</FlowDocument>
</RichTextBox>
最后添加一條訊息:
rtb.PrintMessage("Some_Message");
rtb.ScrollToEnd();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506687.html
