在 WPF WebBrowser 控件中显示字符串中的 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2585782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:39:09  来源:igfitidea点击:

Displaying html from string in WPF WebBrowser control

wpfwebbrowser-control

提问by Andrey

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?

我的数据上下文对象包含一个字符串属性,它返回我需要在 WebBrowser 控件中显示的 html;我找不到 WebBrowser 的任何属性来绑定它。有任何想法吗?

Thanks!

谢谢!

回答by Abe Heidebrecht

The WebBrowserhas a NavigateToStringmethod 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:

WebBrowser有一个NavigateToString方法,你可以用它来导航到HTML内容。如果您希望能够绑定到它,您可以创建一个附加属性,该属性可以在值更改时调用该方法:

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 lclis the xmlns-namespace-alias):

你会像这样使用它(lclxmlns-namespace-alias在哪里):

<WebBrowser lcl:BrowserBehavior.Html="{Binding HtmlToDisplay}" />