69

My data context object contains a string property that returns html that I need to display in WebBrowser control; I can't find any properties of WebBrowser to bind it to. Any ideas?

Thanks!

Andrey
  • 20,487
  • 26
  • 108
  • 176

1 Answers1

133

The WebBrowser has a NavigateToString method that you can use to navigate to HTML content. If you want to be able to bind to it, you can create an attached property that can just call the method when the value changes:

public static 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 d, DependencyPropertyChangedEventArgs e)
    {
        WebBrowser wb = d as WebBrowser;
        if (wb != null)
            wb.NavigateToString(e.NewValue as string);
    }
}

And you would use it like so (where lcl is the xmlns-namespace-alias):

<WebBrowser lcl:BrowserBehavior.Html="{Binding HtmlToDisplay}" />
MrWombat
  • 649
  • 9
  • 19
Abe Heidebrecht
  • 30,090
  • 7
  • 62
  • 66
  • Second argument for OnHtmlChanged should be of type DependencyPropertyChangedEventArgs. – Adam Larsen Aug 26 '10 at 17:38
  • I added this to my code but it does not allow me to edit (a required feature). I am fairly new to wpf so I am unsure of what to change to allow me to edit the html. – scott.smart Dec 21 '11 at 20:50
  • The WebBrowser control displays HTML. If you want to be able to edit the HTML, you will have to use another control, like TextBox or RichTextBox. – Abe Heidebrecht Jan 19 '12 at 16:32
  • 3
    this answer is incomplete - what's PinnedInstrumentsViewModel, in which class do I even put this? this is basically the same answer but ready to go : http://stackoverflow.com/a/4204350/16940 – Simon_Weaver Jul 05 '14 at 09:51
  • 1
    @Simon_Weaver, you're correct, and that was a dumb type. I've updated it so it makes more sense. – Abe Heidebrecht Mar 17 '15 at 20:01
  • Webbrowser does support editing using design mode: `var doc = browser.Document as HTMLDocument; doc.designMode = "On";` – Ole K Apr 06 '16 at 09:07