用于文本装饰的 wpf c# 函数

wpf c# function for text decoration

我正在将 Powershell 脚本转换为 WPF C# 脚本。我正在尝试转换将文本添加到 richtextbox 并指定颜色的 powershell 函数。我目前多次使用相同的代码,我知道这是低效的。我想要的是一个 function/method ,每当我分配新的文本和颜色时我都可以重复使用它。这是我拥有的:

富文本框在 WPF 上看起来像这样 xml

<RichTextBox x:Name="richBox"
             Grid.Row="3"
             Grid.ColumnSpan="3"
             Margin="10,10,10,10"
             HorizontalAlignment="Left">
</RichTextBox>

这是我的 C# 代码

TextRange rtbRange = new TextRange(richBox.Document.ContentEnd, richBox.Document.ContentEnd);
rtbRange.Text = "Add some text here";
rtbRange.ApplyPropertyValue(TextElement.ForegroundProperty, System.Windows.Media.Brushes.DodgerBlue);

//some code is here

TextRange rtbRange2 = new TextRange(richBox.Document.ContentEnd, richBox.Document.ContentEnd);
rtbRange2.Text = "add some more text later with the same property value";
rtbRange2.ApplyPropertyValue(TextElement.ForegroundProperty, System.Windows.Media.Brushes.DodgerBlue);

//some more code is here

TextRange rtbRange3 = new TextRange(richBox.Document.ContentEnd, richBox.Document.ContentEnd);
rtbRange3.Text = "add some more text later with a different color";
rtbRange3.ApplyPropertyValue(TextElement.ForegroundProperty, System.Windows.Media.Brushes.DarkGreen);

类似的 powershell 函数:

function add2RTB{
 Param([string]$rtbText, 
       [string]$rtbColor = "Black")
   $RichTextRange = New-Object System.Windows.Documents.TextRange( 
   $syncHash.richBox.Document.ContentEnd,$syncHash.richBox.Document.ContentEnd ) 
   $RichTextRange.Text = $rtbText 
   $RichTextRange.ApplyPropertyValue(([System.Windows.Documents.TextElement]::ForegroundProperty ), $rtbColor) 
}
#Usage: 
add2RTB -rtbText "adding some text" -rtbColor "DodgerBlue"
#some code here
add2RTB -rtbText "adding more text" -rtbColor "DarkGreen"

在 C# 中是否有类似于 powershell 函数的方法或函数用于 WPF?我对 C# 还是很陌生,转换我从 powershell 知道的有时复杂的脚本是一个陡峭的学习曲线。

只需将 PS 函数 'add2RTB' 翻译成 C#。
它与 Powershell 中的一样,两个参数和一个 TextRange 来创建...

using System.Windows.Media;
...

void Add2RTB (string text, Brush brush) {
   var rtbRange = new TextRange(richBox.Document.ContentEnd, richBox.Document.ContentEnd) { Text = text };
   rtbRange.ApplyPropertyValue(TextElement.ForegroundProperty, brush);
}

// usage:    

Add2RTB ("Add some text here", Brushes.DodgerBlue);
//some code is here
Add2RTB ("add some more text later with the same property value", Brushes.DodgerBlue);
//some more code is here
Add2RTB ("add some more text later with a different color", Brushes.DarkGreen);