title: How to keep style on open xml documents
body: <p>I am using open XML(Microsoft Word - .docx) as a file template to automatically generate other documents. In the template document I have defined content controls, and I have written code to replace content in these content controls. </p>
  
  <p>The content is replaced and the documents are generated, but I am struggling with keeping the style. In Word, when inspecting properties of the content control, I have checked the checbox for "Use a style to format text into the empty control: style", and also checked for "Remove content controls when content are edited". This doesn't seem to have any impact when documents are generated by code. </p>
  
  <p><img src="https://i.stack.imgur.com/M8bAX.png" alt="Here is how I set the properties of the content control in Word">
  This is my code (which a community member here was kind enough to help with) for replacing the data in the content controls. Any ideas what I should do in order to keep the formatting? The formatting is simple text formatting, like size and font. Please advice: </p>
  
  <pre><code>    private static void ReplaceTags(MainDocumentPart mainPart, string tagName, string tagValue)
      {
          //grab all the tag fields
          var tagFields = mainPart.Document.Body.Descendants&lt;SdtBlock&gt;().Where
              (r =&gt; r.SdtProperties.GetFirstChild&lt;Tag&gt;().Val == tagName);
  
          foreach (var field in tagFields)
          {
              //remove all paragraphs from the content block
              field.SdtContentBlock.RemoveAllChildren&lt;DocumentFormat.OpenXml.Wordprocessing.Paragraph&gt;();
              //create a new paragraph containing a run and a text element
              var newParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
              var newRun = new DocumentFormat.OpenXml.Wordprocessing.Run();
              var newText = new DocumentFormat.OpenXml.Wordprocessing.Text(tagValue);
              newRun.Append(newText);
              newParagraph.Append(newRun);
              //add the new paragraph to the content block
              field.SdtContentBlock.Append(newParagraph);
          }
      }
  </code></pre>