Displaying html from string in WPF WebBrowser control

WpfWebbrowser Control

Wpf Problem Overview


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!

Wpf Solutions


Solution 1 - Wpf

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}" />

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreyView Question on Stackoverflow
Solution 1 - WpfAbe HeidebrechtView Answer on Stackoverflow