Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I bind HTML to a WPF Web Browser Control?

Tags:

browser

wpf

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?

like image 661
Jiew Meng Avatar asked Nov 17 '10 09:11

Jiew Meng


Video Answer


1 Answers

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}" />
like image 187
Fredrik Hedblad Avatar answered Sep 20 '22 10:09

Fredrik Hedblad