Export (0) Print
Expand All

How to: Change Styles on an Element in the Managed HTML Document Object Model

You can use styles in HTML to control the appearance of a document and its elements. HtmlDocument and HtmlElement support Style properties that take style strings of the following format:

name1:value1;...;nameN:valueN;

Here is a DIV with a style string that sets the font to Arial and all text to bold:

<DIV style="font-face:arial;font-weight:bold;">

Hello, world!

</DIV>

The problem with manipulating styles using the Style property is that it can prove cumbersome to add to and remove individual style settings from the string. For example, it would become a complex procedure for you to render the previous text in italics whenever the user positions the cursor over the DIV, and take italics off when the cursor leaves the DIV. Time would become an issue if you need to manipulate a large number of styles in this manner.

The following procedure contains code that you can use to easily manipulate styles on HTML documents and elements. The procedure requires that you know how to perform basic tasks in Windows Forms, such as creating a new project and adding a control to a form.

To process style changes in a Windows Forms application

  1. Create a new Windows Forms project.

  2. Create a new class file ending in the extension appropriate for your programming language.

  3. Copy the StyleGenerator class code in the Example section of this topic into the class file, and save the code.

  4. Save the following HTML to a file named Test.htm.

    <HTML>
        <BODY>
    
            <DIV style="font-face:arial;font-weight:bold;">
                Hello, world!
            </DIV><P>
    
            <DIV>
                Hello again, world!
            </DIV><P>
    
        </BODY>
    </HTML>
    
  5. Add a WebBrowser control named webBrowser1 to the main form of your project.

  6. Add the following code to your project's code file.

    NoteImportant

    Ensure that the webBrowser1_DocumentCompleted event hander is configured as a listener for the DocumentCompleted event. In Visual Studio, double-click on the WebBrowser control; in a text editor, configure the listener programmatically.

    StyleGenerator sg = null;
    HtmlElement elem = null;
    
    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        sg = new StyleGenerator();
    
        webBrowser1.Document.MouseOver += new HtmlElementEventHandler(Document_MouseOver);
        webBrowser1.Document.MouseLeave += new HtmlElementEventHandler(Document_MouseLeave);
    }
    
    void Document_MouseOver(object sender, HtmlElementEventArgs e)
    {
        elem = webBrowser1.Document.GetElementFromPoint(e.MousePosition);
        if (elem.TagName.Equals("DIV"))
        {
            sg.ParseStyleString(elem.Style);
            sg.SetStyle("font-style", "italic");
            elem.Style = sg.GetStyleString();
        }
    }
    
    void Document_MouseLeave(object sender, HtmlElementEventArgs e)
    {
        if (elem != null)
        {
            sg.RemoveStyle("font-style");
            elem.Style = sg.GetStyleString();
            // Reset, since we may mouse over a new DIV element next time.
            sg.Clear();
        }
    }
    
    
  7. Run the project. Run your cursor over the first DIV to observe the effects of the code.

Example

The following code example shows the full code for the StyleGenerator class, which parses an existing style value, supports adding, changing, and removing styles, and returns a new style value with the requested changes.

using System;
using System.Collections.Generic;
using System.Text;

namespace ManagedDOMStyles
{
    public class StyleGenerator
    {
        private Dictionary<string, string> styleDB;

        public StyleGenerator()
        {
            styleDB = new Dictionary<string, string>();
        }

        public bool ContainsStyle(string name)
        {
            return(styleDB.ContainsKey(name));
        }

        public string SetStyle(string name, string value)
        {
            string oldValue = "";

            if (!(name.Length > 0))
            {
                throw (new ArgumentException("Parameter name cannot be zero-length."));
            }
            if (!(value.Length > 0))
            {
                throw (new ArgumentException("Parameter value cannot be zero-length."));
            }

            if (styleDB.ContainsKey(name))
            {
                oldValue = styleDB[name];
            }

            styleDB[name] = value;

            return (oldValue);
        }

        public string GetStyle(string name)
        {
            if (!(name.Length > 0))
            {
                throw (new ArgumentException("Parameter name cannot be zero-length."));
            }

            if (styleDB.ContainsKey(name))
            {
                return (styleDB[name]);
            }
            else
            {
                return ("");
            }
        }

        public void RemoveStyle(string name)
        {
            if (styleDB.ContainsKey(name))
            {
                styleDB.Remove(name);
            }
        }

        public string GetStyleString()
        {
            if (styleDB.Count > 0)
            {
                StringBuilder styleString = new StringBuilder("");
                foreach (string key in styleDB.Keys)
                {
                    styleString.Append(String.Format("{0}:{1};", (object)key, (object)styleDB[key]));
                }

                return (styleString.ToString());
            }
            else
            {
                return ("");
            }
        }

        public void ParseStyleString(string styles)
        {
            if (styles.Length > 0)
            {
                string[] stylePairs = styles.Split(new char[] { ';' });
                foreach(string stylePair in stylePairs)
                {
                    if (stylePairs.Length > 0)
                    {
                        string[] styleNameValue = stylePair.Split(new char[] { ':' });
                        if (styleNameValue.Length == 2)
                        {
                            styleDB[styleNameValue[0]] = styleNameValue[1];
                        }
                    }
                }
            }
        }

        public void Clear()
        {
            styleDB.Clear();
        }
    }
}

See Also

Reference

HtmlElement

Community Additions

ADD
Show:
© 2014 Microsoft