Can I bind HTML to a WPF Web Browser Control?

See this question.

To summarize, first you create an Attached Property for WebBrowser

public class BrowserBehavior
{
    public static readonly DependencyProperty HtmlProperty = DependencyProperty.RegisterAttached(
            "Html",
            typeof(string),
            typeof(BrowserBehavior),
            new FrameworkPropertyMetadata(OnHtmlChanged));

    [AttachedPropertyBrowsableForType(typeof(WebBrowser))]
    public static string GetHtml(WebBrowser d)
    {
        return (string)d.GetValue(HtmlProperty);
    }

    public static void SetHtml(WebBrowser d, string value)
    {
        d.SetValue(HtmlProperty, value);
    }

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

And then you can Bind to your html string and NavigateToString will be called everytime your html string changes

<WebBrowser local:BrowserBehavior.Html="{Binding MyHtmlString}" />

Leave a Comment