21

Suppose I have a property HTML (string). Can I bind that to a WPF WebBrowser control? There is the Source property where I need a URI, but if I have a HTML string in memory I want to render, can I do that? I am using MVVM, so I think its harder to use methods like webBrowser1.NavigateToString() etc? cos I won't know the control name?

Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

1 Answers1

61

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}" />
Community
  • 1
  • 1
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
  • This is a nice trick. However when trying to embed a WebBrowser inside a DataTemplate (for instance, when templating combobox's item) it doesn't seem to work (for some reason the OnHtmlChanged is get raised twice, the second time with null). – Tomer Apr 23 '12 at 08:55
  • @tomer I had the same problem so I just changed e.NewValue as string to e.NewValue as string ?? " ". I edited the code to reflect this. – Simon_Weaver Jul 06 '14 at 22:05