How To: Dynamic CSS Action Panes in Office

In my last post How to Create HTML Action Panes for Word and Excel using VSTO 2005 I showed a simple but powerful technique to use HTML pages in the Word or Excel Task Pane. In this post I will show you how to extend this to use dynamic Cascading Style Sheets (CSS). Dynamic CSS allows you to swap style sheets on the fly at runtime. This allows you to change the look and feel of your application in response to events in Office.

The first thing we need to do is create our CSS files. In this example I create 3 very simple files that just change the background color.

CSS1.cs

BODY

{

            background-color:Aqua;

}

CSS2.cs

BODY

{

            background-color:Fuchsia;

}

CSS3.cs

BODY

{

            background-color:Blue;

}

Now we need to define them in our HTML page that will be loaded in the Office task pane.(see previous post on how to do this ) . First define the active stylesheet using the link tag. Then define the alternate stylesheets using the link tag and rel attribute of "alternate stylesheet" see example below. Next create a jscript function to set one of the alternate sheets to be the active sheet. This function, setActiveStyleSheet, will be called from our VSTO solution.

<html xmlns="https://www.w3.org/1999/xhtml">

<head>

    <title>HTML1</title>

    <!--Define the stylesheets-->

    <link rel="stylesheet" type="text/css" href="CSS1.css" title="Preferred" />

    <link rel="alternate stylesheet" type="text/css" href="CSS1.css" title="CSS1" />

    <link rel="alternate stylesheet" type="text/css" href="CSS2.css" title="CSS2" />

    <link rel="alternate stylesheet" type="text/css" href="CSS3.css" title="CSS3" />

    <!-- function to change the active CSS-->

    <script type="text/jscript">

        function setActiveStyleSheet(title)

        {

            var i, a, main;

            for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {

                if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))

                {

                    a.disabled = true;

                    if(a.getAttribute("title") == title) a.disabled = false;

                }

            }

        }

    </script>

</head>

<body>

    <p>

        HTML1</p>

     <!--Call a function on the WinForm-->

    <button onclick="window.external.RefreshDocument()">

        Refresh Document</button>

</body>

</html>

All that is left to do is call the jscript function to set the active stylesheet from our VSTO soluction. The call looks like this. Note Html1UserControl is a reference to the user control that contains the HTML page above.

    Private Sub SetActiveStyleSheet(ByVal CSS_Title As String)

        'Change the CSS on the HTML page

        Dim args As Object() = {CSS_Title}