Jaa


Changing HTML page title from Silverlight

Recently I wrote following Silverlight code and got stuck with the runtime error (as being commented below).

            ScriptObjectCollection soc = HtmlPage.Document.GetElementsByTagName("Title");

            if (soc != null && soc.Count > 0)

            {

                HtmlElement titleElement = (HtmlElement)soc[0];

                string title = (string)titleElement.GetProperty("innerHTML");

                // the code below will give me runtime error

                titleElement.SetProperty("innerHTML", title + " :-)");

            } 

Basically the code logic is to get the reference to <TITLE> element, and then get the inner html text and set it with new value. I wonder why I could not set the innerHTML property of the element even though I could get the html page title using the same property. I posted my question to our Silverlight internal forum, and learned that the innerHTML property is read-only for <TITLE> element (and some other elements which is actually documented here), and the MSDN documentation also mentions that we can change the value of <TITLE> element by assigning document.title properly. Therefore, my code above needs to be changed to:

            ScriptObjectCollection soc = HtmlPage.Document.GetElementsByTagName("Title");

            if (soc != null && soc.Count > 0)

            {

                HtmlElement titleElement = (HtmlElement)soc[0];

                string title = (string)titleElement.GetProperty("innerHTML");

                HtmlPage.Document.SetProperty("title", title + " :-)");

            }

It works perfectly now (the page title changes). I hope this helps in case you run into the same problem.

Comments