我正在將 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# 中是否有與 powershell 函式類似的用于 WPF 的方法或函式?我對 C# 還是很陌生,轉換我從 powershell 知道的有時復雜的腳本是一個陡峭的學習曲線。
uj5u.com熱心網友回復:
只需將 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/481286.html
