开发者

Can I bind HTML to a WPF Web Browser Control?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜