Johannes Schacht
Johannes Schacht

Reputation: 1334

control style in WebBrowser control

I have an error return string that is sometimes plain text and sometimes HTML. My idea is to display that in a WebBrowser control. I found this article that showed how to assign a string as content for a webBrowser. This is my XAML:

<WebBrowser
            local:BrowserBehavior.Html="{Binding ElementName=resultListBox, Path=SelectedItem.Details}" 
            Width="400" MinHeight="50" Margin="0">
        </WebBrowser>

It works fine but plain strings are displayed in some times roman font. Is there a way to inject a style sheet into the WebBrowser control? Or is there a better solution to my problem in the first place?

Upvotes: 0

Views: 1853

Answers (1)

Szabolcs D&#233;zsi
Szabolcs D&#233;zsi

Reputation: 8843

You can do this in your attached property's code:

static void OnHtmlChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
    WebBrowser webBrowser = dependencyObject as WebBrowser;
    webBrowser.LoadCompleted += WebBrowserOnLoadCompleted;
    if (webBrowser != null)
        webBrowser.NavigateToString(e.NewValue as string ?? "&nbsp;");
}

private static void WebBrowserOnLoadCompleted(object sender, NavigationEventArgs navigationEventArgs)
{
    var webBrowser = sender as WebBrowser;

    if (webBrowser != null)
    {
        var document = webBrowser.Document as mshtml.HTMLDocument;

        if (document != null)
        {
            var head = document.getElementsByTagName("head").OfType<mshtml.HTMLHeadElement>().FirstOrDefault();

            if (head != null)
            {
                var styleSheet = (mshtml.IHTMLStyleSheet)document.createStyleSheet("", 0);
                styleSheet.cssText = "* { background-color: purple; " +
                                     "    font-family: Arial, Helvetica, sans-serif; " +
                                     " /* set whatever CSS rule you want */ }";
            }
        }

        webBrowser.LoadCompleted -= WebBrowserOnLoadCompleted;
    }
}

You have to include Microsoft.mshtml reference for this to work.

This attaches a LoadCompleted event handler before navigating to the string. In the handler it gets the head element, creates a new style tag and adds the CSS rules you want.

Upvotes: 1

Related Questions