Inserting HTML at current Caret position

It is a very common need for a developer to insert custom HTML dynamically based on user's action. The most useful method for doing so is using the InsertHtml method.

Here is an example. Say you have a button in your application and you want that, if the user clicks that button, a rich snippet will be inserted at the caret location. Say the instance name of your editor is 'wpfHtmlEditor1' and the click event handler for that button is 'CustomToolbarButton_OnClick'.

Custom toolbar button click event handler

Now, within that click event handler, you can write code like this:

C#

private void CustomToolbarButton_OnClick(object sender, RoutedEventArgs e)
{
    wpfHtmlEditor1.Content.InsertHtml(
        "<span style='color:red;'>Hello</span> <span style='color:blue;'>World</span>", 
        keepSelected: true);
}

VB

Private Sub CustomToolbarButton_OnClick(sender As Object, e As RoutedEventArgs)
    wpfHtmlEditor1.Content.InsertHtml("<span style='color:red;'>Hello</span> <span style='color:blue;'>World</span>", keepSelected := True)
End Sub
Now, you can run the application. Let's say you have following text in your application and your caret is at the beginning of the word 'awesome'.

Before Insert

Now, simply click that new button that you just created on the toolbar. You will see your expected snippet inserted as follows:

After Insert

You see that the inserted snippet is highlighted. That is because we passed the second argument of the method "keepSelected = true". If you pass that argument as false, then the inserted snippet will not be highlighted upon insertion. Anyway, once you deselect that part, you will see the snippet as follows:

After Deselect

Last updated on 21 August 2016, Sunday, 2:19:29 PM
If you have any questions or concerns about this tutorial, Please feel free to share your comment.