在 WPF WebBrowser 控件中显示字符串中的 html [英] Displaying html from string in WPF WebBrowser control

查看:38
本文介绍了在 WPF WebBrowser 控件中显示字符串中的 html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 有一个 NavigateToString 方法,可用于导航到 HTML 内容.如果你想能够绑定到它,你可以创建一个附加的属性,当值改变时可以调用该方法:

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:

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);
    }
}

你会像这样使用它(其中 lcl 是 xmlns-namespace-alias):

And you would use it like so (where lcl is the xmlns-namespace-alias):

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

这篇关于在 WPF WebBrowser 控件中显示字符串中的 html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆