70

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?

1 Answer 1

137

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}" />
Sign up to request clarification or add additional context in comments.

6 Comments

Second argument for OnHtmlChanged should be of type DependencyPropertyChangedEventArgs.
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.
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.
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 : stackoverflow.com/a/4204350/16940
@Simon_Weaver, you're correct, and that was a dumb type. I've updated it so it makes more sense.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.