开发者

Can I bind HTML to a WPF Web Browser Control?

开发者 https://www.devze.com 2023-01-25 18:09 出处:网络
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, ca开发者_

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, ca开发者_运维问答n 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?


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

精彩评论

暂无评论...
验证码 换一张
取 消