Content Service

The Content service (MyEditor.Content, type IContentService) is the primary surface for programmatic edits to the live HTML document hosted by a WpfHtmlEditor control. It exposes get/set methods for body and document HTML, structural inserts (HTML fragments, horizontal rules, plain text, script blocks), file load/save helpers, head-element manipulation, base64 image embedding, mail-merge placeholder insertion, and table authoring.

The service is owned by the editor and is created when the control is constructed. Do not create your own instance; always access it through MyEditor.Content. The service implements IDisposable; the editor disposes it automatically when the parent window closes. Methods that read or modify the live document require the editor to be in EditorModes.WysiwygDesign; calls made in HtmlEdit or Preview mode either do nothing or operate on the last-loaded document depending on the method.

GetBodyText Method

Returns the body's textual content with HTML markup stripped. Whitespace is collapsed per the browser's default rendering rules.

Syntax
string GetBodyText();
Returns

string -- the plain-text body content.

Remarks

See GetFormattedPlainText for an alternative implementation that preserves more of the document's visual line structure.

Example
string body = MyEditor.Content.GetBodyText();
Console.WriteLine($"Plain body has {body.Length} chars");

GetFormattedPlainText Method

Returns the document's text content with HTML markup stripped, using a formatting algorithm that preserves block-level line breaks. Alternative to GetBodyText when the visual line structure matters (e.g. piping to a plain-text email body).

Syntax
string GetFormattedPlainText();
Returns

string -- the formatted plain text.

Example
string formatted = MyEditor.Content.GetFormattedPlainText();
File.WriteAllText(@"C:\temp\export.txt", formatted);

SetBodyText Method

Replaces the body with the given plain text. HTML special characters in the input are escaped.

Syntax
void SetBodyText(string text);
Parameters
NameTypeDescription
textstringThe text to set as the body content.
Example
MyEditor.Content.SetBodyText("Quarterly report draft - 2026 Q1");

GetBodyHtml Method

Returns the HTML between the <body> and </body> tags. Pass true for getInXhtml to receive well-formed XHTML (self-closing void tags, lowercase tag names); pass false for raw HTML.

Syntax
string GetBodyHtml(bool getInXhtml);
Parameters
NameTypeDescription
getInXhtmlbooltrue to receive XHTML-clean output; false for raw MSHTML output.
Returns

string -- the body HTML.

Example
string xhtml = MyEditor.Content.GetBodyHtml(getInXhtml: true);
XDocument doc = XDocument.Parse("<root>" + xhtml + "</root>");

SetBodyHtml Method

Replaces the document's body HTML.

Syntax
void SetBodyHtml(string bodyHtml);
Parameters
NameTypeDescription
bodyHtmlstringThe new inner HTML of the body.
Example
MyEditor.Content.SetBodyHtml("<h1>Welcome</h1><p>Edit me.</p>");

GetDocumentHtml Method

Returns the full HTML document including the <html>, <head>, and <body> markup.

Syntax
string GetDocumentHtml();
Returns

string -- the complete HTML document.

Example
string fullDoc = MyEditor.Content.GetDocumentHtml();
File.WriteAllText(@"C:\temp\out.html", fullDoc, Encoding.UTF8);

SetDocumentHtml Method

Replaces the entire HTML document.

Syntax
void SetDocumentHtml(string docHtml);
Parameters
NameTypeDescription
docHtmlstringThe new HTML document including <html>, <head> and <body>.
Example
string template = File.ReadAllText(@"C:\templates\letter.html");
MyEditor.Content.SetDocumentHtml(template);

GetDocumentXml Method

Returns the document serialized as XML (XHTML-equivalent markup). Useful for pipelines that expect XML rather than HTML on the wire.

Syntax
string GetDocumentXml();
Returns

string -- the document as XML.

Example
string xml = MyEditor.Content.GetDocumentXml();
XDocument.Parse(xml).Save(@"C:\temp\doc.xml");

GetBodyStyleAsDom Method

Returns the body element's style object as an MSHTML IHTMLStyle COM pointer for direct property-level access (font-family, color, padding, etc.) without parsing the style string.

Syntax
IHTMLStyle GetBodyStyleAsDom();
Returns

mshtml.IHTMLStyle -- the body's live style object.

Example
IHTMLStyle style = MyEditor.Content.GetBodyStyleAsDom();
if (style != null)
{
    style.backgroundColor = "#fafafa";
    style.color = "#222";
}

GetBodyStyle Method

Returns the value of the style attribute on the body element as a single CSS string.

Syntax
string GetBodyStyle();
Returns

string -- the inline body CSS rules.

Example
string css = MyEditor.Content.GetBodyStyle();
Debug.WriteLine($"Body inline CSS = {css}");

SetBodyStyle Method

Sets the value of the style attribute on the body element.

Syntax
void SetBodyStyle(string styleValue);
Parameters
NameTypeDescription
styleValuestringThe CSS rules to place on the body style attribute.
Example
MyEditor.Content.SetBodyStyle("font-family:Segoe UI; padding:12px; color:#222;");

GetBodyClassName Method

Returns the value of the class attribute on the document's body element. Equivalent to reading WpfHtmlEditor.BodyCSSClassName.

Syntax
string GetBodyClassName();
Returns

string -- the body class name, or empty if no class is set.

Example
if (MyEditor.Content.GetBodyClassName() != "dark")
    MyEditor.Content.SetBodyClassName("dark");

SetBodyClassName Method

Sets the value of the class attribute on the document's body element. Equivalent to writing WpfHtmlEditor.BodyCSSClassName.

Syntax
void SetBodyClassName(string className);
Parameters
NameTypeDescription
classNamestringThe CSS class name; pass null or empty to clear.
Example
MyEditor.Content.SetBodyClassName("print-preview");

GetAllLinkHrefs Method

Returns the href values of every <a> hyperlink in the document, in document order.

Syntax
string[] GetAllLinkHrefs();
Returns

string[] -- the array of hyperlink hrefs; empty array if there are no hyperlinks.

Example
foreach (string href in MyEditor.Content.GetAllLinkHrefs())
{
    if (!Uri.IsWellFormedUriString(href, UriKind.Absolute))
        Debug.WriteLine($"Broken link: {href}");
}

GetAllImageSources Method

Returns the src values of every <img> element in the document, in document order.

Syntax
string[] GetAllImageSources();
Returns

string[] -- the array of image source values; empty array if there are no images.

Example
string[] images = MyEditor.Content.GetAllImageSources();
MessageBox.Show($"Document references {images.Length} image(s).");

InsertHtml Method

Inserts an HTML fragment at the current caret position without losing focus. The canonical way to inject content from a custom toolbar button. Script blocks are not inserted by this method -- use InsertScript or InsertHtmlBetweenHead instead.

Syntax
void InsertHtml(string htmlText, bool keepSelected);
Parameters
NameTypeDescription
htmlTextstringThe HTML fragment to insert.
keepSelectedboolIf true, the inserted fragment is left selected after insertion; otherwise the caret is placed after it.
Example
MyEditor.Content.InsertHtml("<strong>Hello</strong>", keepSelected: false);

InsertText Method

Inserts a plain-text string at the current caret position. HTML entities in the input are escaped (so < becomes &lt;).

Syntax
void InsertText(string text);
Parameters
NameTypeDescription
textstringThe text to insert.
Example
MyEditor.Content.InsertText(DateTime.Now.ToString("yyyy-MM-dd HH:mm"));

InsertHorizontalRule Method

Inserts an <hr> element at the current caret position.

Syntax
void InsertHorizontalRule();
Example
private void DividerButton_Click(object sender, RoutedEventArgs e)
{
    MyEditor.Content.InsertHorizontalRule();
}

InsertScript Method

Inserts a <script> block at the current caret position. Provided because InsertHtml deliberately filters out script content.

Syntax
void InsertScript(string scriptMarkUp);
Parameters
NameTypeDescription
scriptMarkUpstringThe script markup to insert.
Example
MyEditor.Content.InsertScript("<script>console.log('hi');</script>");

InsertHtmlBetweenHead Method

Appends the given HTML to the document's <head> section. Use this to inject <meta>, <link>, <style>, or <script> elements that should live in the head rather than the body.

Syntax
void InsertHtmlBetweenHead(string insertingHtml);
Parameters
NameTypeDescription
insertingHtmlstringThe HTML to insert into the head.
Example
MyEditor.Content.InsertHtmlBetweenHead(
    "<style id='theme'>body { background:#222; color:#eee; }</style>");

RemoveHtmlElementFromHeadByTag Method

Removes every element with the given tag name from the document <head>. Pass meta to clear all meta tags or style to clear all inline style blocks. Tag matching is case-insensitive.

Syntax
void RemoveHtmlElementFromHeadByTag(string tagName);
Parameters
NameTypeDescription
tagNamestringThe tag name to match (case-insensitive).
Example
// Clear all stylesheet links before reapplying a fresh theme.
MyEditor.Content.RemoveHtmlElementFromHeadByTag("link");

RemoveHtmlElementFromHeadById Method

Removes the element with the given id from the document <head>. Useful for clearing stale <style> or <link> blocks the host app injected earlier.

Syntax
void RemoveHtmlElementFromHeadById(string id);
Parameters
NameTypeDescription
idstringThe id of the head element to remove.
Example
MyEditor.Content.RemoveHtmlElementFromHeadById("theme");

RemoveHtmlElementById Method

Removes the element with the given id from anywhere in the document. No-op if no matching element exists.

Syntax
void RemoveHtmlElementById(string id);
Parameters
NameTypeDescription
idstringThe id of the element to remove.
Example
MyEditor.Content.RemoveHtmlElementById("legacyBanner");

ChangeElementId Method

Renames an element's id attribute from oldId to newId. No-op if no element with oldId exists.

Syntax
void ChangeElementId(string oldId, string newId);
Parameters
NameTypeDescription
oldIdstringThe current id of the element.
newIdstringThe new id to assign.
Example
MyEditor.Content.ChangeElementId("intro", "introduction");

ElementExists Method

Returns whether an element with the given id exists anywhere in the document (head or body).

Syntax
bool ElementExists(string elementId);
Parameters
NameTypeDescription
elementIdstringThe element id to look up.
Returns

bool -- true if an element with that id exists; otherwise false.

Example
if (!MyEditor.Content.ElementExists("footer"))
    MyEditor.Content.InsertHtml("<div id='footer'>(c) 2026</div>", false);

GetAttributeValueOfAnElement Method

Returns the value of the named attribute on the element identified by elementId. Useful for reading the href of a stylesheet link or the content of a meta tag in the document head.

Syntax
string GetAttributeValueOfAnElement(string elementId, string attributeName);
Parameters
NameTypeDescription
elementIdstringThe id of the element to inspect.
attributeNamestringThe attribute name to read.
Returns

string -- the attribute value, or null/empty if the element or attribute is absent.

Example
string href = MyEditor.Content.GetAttributeValueOfAnElement("mainLink", "href");

SetAttributeValueOfAnElement Method

Sets the value of an attribute on the element identified by elementId. Use this to update a head-element attribute (such as a stylesheet link's href) without rewriting the entire document head.

Syntax
void SetAttributeValueOfAnElement(string elementId, string attributeName, string value);
Parameters
NameTypeDescription
elementIdstringThe id of the element to update.
attributeNamestringThe attribute name to set.
valuestringThe new attribute value.
Example
MyEditor.Content.SetAttributeValueOfAnElement("logo", "alt", "Company logo");

GetOuterHtmlOfAnElement Method

Returns the outer HTML (element + its child markup) of the element identified by elementId.

Syntax
string GetOuterHtmlOfAnElement(string elementId);
Parameters
NameTypeDescription
elementIdstringThe id of the element to inspect.
Returns

string -- the element's outer HTML, or null if not found.

Example
string outerHtml = MyEditor.Content.GetOuterHtmlOfAnElement("intro");
Debug.WriteLine(outerHtml);

GetInnerHtmlOfAnElement Method

Returns the inner HTML (child markup) of the element identified by elementId.

Syntax
string GetInnerHtmlOfAnElement(string elementId);
Parameters
NameTypeDescription
elementIdstringThe id of the element to inspect.
Returns

string -- the element's inner HTML, or null if the element is not found.

Example
string innerHtml = MyEditor.Content.GetInnerHtmlOfAnElement("sidebar");

UpdateInnerHtmlOfAnElement Method

Replaces the inner HTML of the element identified by elementId. Existing children are discarded.

Syntax
void UpdateInnerHtmlOfAnElement(string elementId, string newHtml);
Parameters
NameTypeDescription
elementIdstringThe id of the element to update.
newHtmlstringThe new inner HTML.
Example
MyEditor.Content.UpdateInnerHtmlOfAnElement("status", "<b>Updated</b>");

GetHtmlElements Method

Returns a strongly-typed collection of the document's elements. Pass true for onlyBodyElements to limit the walk to elements under <body>; pass false to include head elements as well.

Syntax
HtmlElementCollection GetHtmlElements(bool onlyBodyElements);
Parameters
NameTypeDescription
onlyBodyElementsbooltrue to restrict the walk to body descendants.
Returns

System.Windows.Forms.HtmlElementCollection -- the document's elements.

Example
var elements = MyEditor.Content.GetHtmlElements(onlyBodyElements: true);
foreach (HtmlElement el in elements)
{
    if (el.TagName == "IMG") Debug.WriteLine(el.GetAttribute("src"));
}

GetBodyIHtmlElements Method

Returns the body's child elements as an MSHTML IHTMLElementCollection COM pointer, for callers that need to walk the DOM directly.

Syntax
IHTMLElementCollection GetBodyIHtmlElements();
Returns

mshtml.IHTMLElementCollection -- the live element collection.

Example
IHTMLElementCollection coll = MyEditor.Content.GetBodyIHtmlElements();
foreach (IHTMLElement el in coll)
    Debug.WriteLine(el.tagName);

GetHtmlElementAt Method

Returns the topmost HTML element under the given pixel point inside the editor's document. Useful when implementing custom mouse-driven UI such as drag-targets or hit-test overlays.

Syntax
IHTMLElement GetHtmlElementAt(Point caretPosition);
Parameters
NameTypeDescription
caretPositionSystem.Drawing.PointPixel coordinates inside the editor document.
Returns

mshtml.IHTMLElement -- the element at that point, or null if none.

Example
IHTMLElement hit = MyEditor.Content.GetHtmlElementAt(new System.Drawing.Point(120, 80));
if (hit != null) Debug.WriteLine($"Hit: {hit.tagName}#{hit.id}");

EmbedLocalImagesAsBase64 Method

Walks the document, finds every <img> element whose src is a local file path or file:// URL, reads each file, and rewrites the src as a data:image/...;base64,... URI. After this call the document is self-contained -- safe to email or save as a single HTML file.

Syntax
void EmbedLocalImagesAsBase64();
Example
MyEditor.Content.EmbedLocalImagesAsBase64();
string portableHtml = MyEditor.Content.GetDocumentHtml();
File.WriteAllText(@"C:\temp\portable.html", portableHtml);

GetEmailMessageWithLocalImagesEmbedded Method

Builds a System.Net.Mail.MailMessage whose body is the current document HTML and whose linked resources contain every local image referenced by the document. Use this to send the editor's content as a properly-formed multipart email without writing your own MIME packaging.

Syntax
MailMessage GetEmailMessageWithLocalImagesEmbedded();
Returns

System.Net.Mail.MailMessage -- the assembled mail message ready to hand to SmtpClient.Send.

Example
using (MailMessage msg = MyEditor.Content.GetEmailMessageWithLocalImagesEmbedded())
{
    msg.From = new MailAddress("you@example.com");
    msg.To.Add("customer@example.com");
    msg.Subject = "Monthly report";
    new SmtpClient("smtp.example.com").Send(msg);
}

LoadBodyHtmlFromFile Method

Reads a file from disk and loads its contents into the editor's body HTML, replacing any existing body content. The remainder of the document (head, doctype) is preserved.

Syntax
void LoadBodyHtmlFromFile(string filePath, Encoding encoding);
Parameters
NameTypeDescription
filePathstringPath to the file to load.
encodingSystem.Text.EncodingText encoding to use when reading the file (e.g. Encoding.UTF8).
Example
MyEditor.Content.LoadBodyHtmlFromFile(@"C:\templates\body.html", Encoding.UTF8);

LoadDocumentHtmlFromFile Method

Reads a file from disk and loads its contents as the entire document HTML, replacing the whole <html>...</html> tree.

Syntax
void LoadDocumentHtmlFromFile(string filePath, Encoding encoding);
Parameters
NameTypeDescription
filePathstringPath to the file to load.
encodingSystem.Text.EncodingText encoding to use when reading the file.
Example
MyEditor.Content.LoadDocumentHtmlFromFile(@"C:\templates\letter.html", Encoding.UTF8);

SaveBodyHtmlToFile Method

Writes the current body HTML to a file on disk.

Syntax
void SaveBodyHtmlToFile(string filePath);
Parameters
NameTypeDescription
filePathstringTarget file path. An existing file is overwritten.
Example
MyEditor.Content.SaveBodyHtmlToFile(@"C:\out\fragment.html");

SaveDocumentHtmlToFile Method

Writes the current full document HTML to a file on disk.

Syntax
void SaveDocumentHtmlToFile(string filePath);
Parameters
NameTypeDescription
filePathstringTarget file path. An existing file is overwritten.
Example
MyEditor.Content.SaveDocumentHtmlToFile(@"C:\out\full.html");

SaveEditorContentAsXml Method

Serializes the document HTML as XML and writes it to a file. Provided for host apps that store editor content as XML rather than HTML.

Syntax
void SaveEditorContentAsXml(string fileName);
Parameters
NameTypeDescription
fileNamestringThe XML file path to write.
Example
MyEditor.Content.SaveEditorContentAsXml(@"C:\out\snapshot.xml");

OpenFile Method

Opens a file and loads its contents into the editor, auto-detecting whether the file holds a body fragment or a full HTML document. Fires the editor's FileOpened event on success.

Syntax
void OpenFile(string filePath);
Parameters
NameTypeDescription
filePathstringPath to the file to open.
Example
var dlg = new Microsoft.Win32.OpenFileDialog { Filter = "HTML files|*.html;*.htm" };
if (dlg.ShowDialog() == true)
    MyEditor.Content.OpenFile(dlg.FileName);

ClearContent Method

Removes all content from the document body, leaving an empty editable surface. The document's head, DOCTYPE, and configured base URL are preserved.

Syntax
void ClearContent();
Example
private void NewDocument_Click(object sender, RoutedEventArgs e)
{
    MyEditor.Content.ClearContent();
}

UpdateBaseUrl Method

Updates the document's base URL used to resolve relative resource paths. Equivalent to assigning WpfHtmlEditor.BaseUrl but does not trigger a behavior repair.

Syntax
void UpdateBaseUrl(string baseUrl);
Parameters
NameTypeDescription
baseUrlstringThe new base URL.
Example
MyEditor.Content.UpdateBaseUrl("https://cdn.example.com/assets/");

GetRightToLeft Method

Returns the right-to-left (RTL) reading direction of the document body.

Syntax
RightToLeft GetRightToLeft();
Returns

System.Windows.Forms.RightToLeft -- one of No, Yes, or Inherit.

Example
RightToLeft rtl = MyEditor.Content.GetRightToLeft();
Debug.WriteLine($"Current RTL mode = {rtl}");

SetRightToLeft Method

Sets the document body's reading direction (RTL/LTR).

Syntax
void SetRightToLeft(RightToLeft rightToLeftValue);
Parameters
NameTypeDescription
rightToLeftValueSystem.Windows.Forms.RightToLeftOne of No, Yes, or Inherit.
Example
MyEditor.Content.SetRightToLeft(RightToLeft.Yes);

ResetTableManipulator Method

Releases and recreates the internal table-manipulation engine. Call this after replacing the document HTML programmatically if subsequent table operations behave unexpectedly.

Syntax
void ResetTableManipulator();
Example
MyEditor.Content.SetBodyHtml(rebuiltHtml);
MyEditor.Content.ResetTableManipulator();

Dispose Method (inherited from IDisposable)

Releases unmanaged resources held by the content service. The control disposes its services automatically when the parent window closes; host applications normally do not call this directly.

Syntax
void Dispose();
Example
// The host control owns disposal -- only call this if you took ownership of the service.
MyEditor.Content.Dispose();

TableAuthoringService Property

Returns (or replaces) the table-authoring service (ITableAuthoringService) used to insert, delete, and merge rows, columns, and cells of the table containing the current selection.

Syntax
ITableAuthoringService TableAuthoringService { get; set; }
Property value

ITableAuthoringService -- the table-authoring service.

Remarks

Members: void InsertColumn(InsertPositions position), void DeleteColumn(), void InsertRow(InsertPositions position), void DeleteRow(), void MergeSelectedCells(), bool CanMergeCells(), void ShowGuidelinesForTablesWithZeroBorder(bool inBackground = false), void HideGuidelinesOfTablesWithZeroBorder(bool inBackground = false), bool IsTableBorderZero(IHTMLElement tableElement), Color SelectedCellBackgroundColor { get; set; }, bool EnableTableCellMerging { get; set; }, ITableManipulator GetTableManipulator(), void ResetTableManipulator(). Cell-merge operations require EnableTableCellMerging == true; the guideline overlay is controlled jointly with Options.ShowZeroBorderGuideline.

Example
var tas = MyEditor.Content.TableAuthoringService;
tas.InsertRow(InsertPositions.Below);
if (tas.CanMergeCells()) tas.MergeSelectedCells();

MailMerge Property

Returns the mail-merge placeholder service (IMailMergeService). The service exposes the host-registered PlaceholderFields list, the InsertPlaceholder(field) method, and the PlaceholderInserted event. Also accessible directly as MyEditor.MailMerge.

Syntax
IMailMergeService MailMerge { get; }
Property value

IMailMergeService -- the mail-merge service.

Remarks

Members: IList<PlaceholderField> PlaceholderFields { get; set; } -- the fields the end user can insert; event EventHandler<PlaceholderInsertedEventArgs> PlaceholderInserted -- fires after each insertion; void InsertPlaceholder(PlaceholderField field) -- inserts a placeholder span at the current caret position. Insertion requires EditorMode == WysiwygDesign.

Example
MyEditor.Content.MailMerge.PlaceholderFields = new List<PlaceholderField>
{
    new PlaceholderField { Name = "FirstName", DisplayLabel = "First Name" },
    new PlaceholderField { Name = "OrderTotal", DisplayLabel = "Order Total" }
};
MyEditor.Content.MailMerge.PlaceholderInserted += (s, e) =>
    Debug.WriteLine($"Inserted {e.Field.Name}: {e.InsertedHtml}");
Last updated on May 12, 2026