在WPF web浏览器控件中显示字符串中的html

时间:2022-11-11 23:07:28

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!

谢谢!

1 个解决方案

#1


103  

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:

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

您可以这样使用它(其中lcl是xmlns-namespace-alias):

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

#1


103  

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:

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

您可以这样使用它(其中lcl是xmlns-namespace-alias):

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