title: wpf c# function for text decoration
body: <p>I am in the process of converting a Powershell script to a WPF C# script. I am trying to convert a powershell function that adds text to the richtextbox and assigns a color. I currently have multiple uses of the same code, which I know is inefficient. What I want is a function/method that I can reuse whenever I am assigning new text and colors. Here is what I have:</p>
  <p>rich text box looks like this on WPF xml</p>
  <pre><code>&lt;RichTextBox x:Name=&quot;richBox&quot;
               Grid.Row=&quot;3&quot;
               Grid.ColumnSpan=&quot;3&quot;
               Margin=&quot;10,10,10,10&quot;
               HorizontalAlignment=&quot;Left&quot;&gt;
  &lt;/RichTextBox&gt;
  </code></pre>
  <p>Here is my C# code</p>
  <pre><code>TextRange rtbRange = new TextRange(richBox.Document.ContentEnd, richBox.Document.ContentEnd);
  rtbRange.Text = &quot;Add some text here&quot;;
  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 = &quot;add some more text later with the same property value&quot;;
  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 = &quot;add some more text later with a different color&quot;;
  rtbRange3.ApplyPropertyValue(TextElement.ForegroundProperty, System.Windows.Media.Brushes.DarkGreen);
  </code></pre>
  <p>Similar powershell function:</p>
  <pre><code>function add2RTB{
   Param([string]$rtbText, 
         [string]$rtbColor = &quot;Black&quot;)
     $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 &quot;adding some text&quot; -rtbColor &quot;DodgerBlue&quot;
  #some code here
  add2RTB -rtbText &quot;adding more text&quot; -rtbColor &quot;DarkGreen&quot;
  </code></pre>
  <p>Is there a method or function in C# for use with WPF that is similar to the powershell function? I am still fairly new to C#, and converting the sometimes complicated scripts that I know from powershell is a steep learning curve.</p>