Adding Context Sensibility to your own buttons
You can change some properties of your custom buttons to reflect the state of the context in the HTML Editor. For example, you may want the checked status to be TRUE for your custom Bold button, Italic Button, Underline Button etc. if the selected or active context is bolded, italic or underlined etc.
Getting Context Information:
You can get the context information by referring to the StateQuery property of WpfHtmlEditor class. This property has members for getting the context status of the editor. You can check if the text is bold by calling htmlEditor1.StateQuery.isBold().
You can refer to the State Query Service page for more details.
Now, let us explain, how can you detect the context changed and use this StateQuery to change your control's properties.
Below is a sample demonstration on how to detect a context change and use this StateQuery to change your control’s properties.
The Editor has an event name SelectionChanged. This SelectionChanged event is fired as soon as you change the caret from one element to another element. We will use this event to update our control’s properties based on context. For this demonstration, we have added our own toolbar and it has three buttons – Bold, Italics and Underline.
1. First we will handle the SelectionChanged event of the Editor.
2. Write the event handler code
C#
private void htmlEditor1_SelectionChanged(object sender, RoutedEventArgs e) { btnBold.Background = htmlEditor1.StateQuery.IsBold() ? Brushes.Yellow : Brushes.LightGray; btnItalics.Background = htmlEditor1.StateQuery.IsItalic() ? Brushes.Yellow : Brushes.LightGray; btnUnderline.Background = htmlEditor1.StateQuery.IsUnderline() ? Brushes.Yellow : Brushes.LightGray; }
VB.NET
Private Sub htmlEditor1_SelectionChanged(sender As Object, e As RoutedEventArgs) btnBold.Background = If(htmlEditor1.StateQuery.IsBold(), Brushes.Yellow, Brushes.LightGray) btnItalics.Background = If(htmlEditor1.StateQuery.IsItalic(), Brushes.Yellow, Brushes.LightGray) btnUnderline.Background = If(htmlEditor1.StateQuery.IsUnderline(), Brushes.Yellow, Brushes.LightGray) End Sub
3. Now run the application, add some text and apply some styling to it. Make some words bold, others italics and underline. When you move the caret, you will notice that the buttons background reflect the formatting of the text. The Bold and Underline buttons’ background color is yellow because the text is bold and underlined.