c# - wpf c# 文本修饰函数

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

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# 中是否有与 WPF 一起使用的类似于 powershell 函数的方法或函数?我对 C# 还是很陌生,转换我从 powershell 知道的有时复杂的脚本是一个陡峭的学习曲线。

回答1

只需将 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);

相似文章

随机推荐

最新文章