Editor for WinForms | ComponentOne
Creating an XHTML Editor in Code / The ToolStripStyles class / Showing and Applying Styles
In This Topic
    Showing and Applying Styles
    In This Topic

    The second combo box in the toolstrip allows users to apply styles to the current selection. It is also implemented in two parts. First, the combo box is populated with the standard XHTML paragraph styles:

    To write code in C#

    C#
    Copy Code
    ToolStripComboBox AddStyleCombo()
    {
        ToolStripComboBox cmb = new ToolStripComboBox();
        cmb.AutoSize = false;
        cmb.Width = 150;
     
        cmb.Items.Add("(None)");
        cmb.Items.Add("Paragraph <p>");
        for (int i = 1; i < 7; i++)
        {
            cmb.Items.Add(string.Format("Heading {0} <h{0}>", i));
        }
        cmb.Items.Add("Unordered List <ul>");
        cmb.Items.Add("Ordered List <ol>");
        cmb.Items.Add("Pre-formatted <pre>");
     
        Items.Add(cmb);
        return cmb;
    }
    Next, three event handlers are used to apply the selected style when the user interacts with the combo box:
    void _cmbStyle_LostFocus(object sender, EventArgs e)
    {
        ValidateAndApplyStyle();
    }
    void _cmbStyle_SelectedIndexChanged(object sender, EventArgs e)
    {
        ValidateAndApplyStyle();
    }
    void _cmbStyle_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            ValidateAndApplyStyle();
        }
    }
    

    Next, three event handlers are used to apply the selected style when the user interacts with the combo box:

    To write code in C#

    C#
    Copy Code
    void ValidateAndApplyStyle()
    {
        string style = _cmbStyle.Text;
        int start = style.IndexOf('<');
        int end = style.IndexOf('>');
        if (end > -1 && end > start)
        {
            var tag = style.Substring(start + 1, end - start - 1);
            Editor.Selection.ApplyTag(tag);
        }
    }
    

    The method starts by retrieving the tag from the combo box, and then applies the style to the current selection using the Selection object's ApplyTag method.

    In addition to the ApplyTag method, the Selection object also provides RemoveTag and IsTagApplied methods for managing the tags applied to the selection.

    Note that although these tags affect the appearance of the document, they are really related to the structure of the document. The actual appearance of a <p> or <h1> tag for example is defined by the style sheet that is currently applied to the document.