将html字符串内容绑定到xaml中的Webview [英] Binding html string content to Webview in xaml

查看:55
本文介绍了将html字符串内容绑定到xaml中的Webview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的xaml中有一个Web视图,如下所示:

I have a webview in my xaml which looks as follows :

<WebView x:Name="WebView" />

然后,在我的代码后面,我有一个名为"htmlcontent"的变量,其中包含html字符串数据,如下所示:

And, in my codebehind I have a variable called "htmlcontent", which contains html string data which looks like as follows :

<html><body><b>Hi there</b></body></html>

如何绑定此html字符串并以XAML的webview组件显示其格式?

How can I bind this html string and display it formatted in the webview component of the XAML?

*编辑-顺便说一句,我正在做Windows 8 Metro应用程序,因此不支持WebBrowser控件

*Edit - By the way, I am doing a Windows 8 metro application, so the WebBrowser control isn't supported

推荐答案

WebView上不存在HtmlString属性(仅是Uri的Source属性).但是您可以做的是为WebView定义一个新的HtmlString附加属性.只需创建以下类:

The HtmlString property does not exist on WebView (only the Source property which is an Uri). But what you can do is to define yourself a new HtmlString attached property for WebView. Just create the following class :

namespace YOURNAMESPACE
{
    class MyProperties
    {
     // "HtmlString" attached property for a WebView
     public static readonly DependencyProperty HtmlStringProperty =
        DependencyProperty.RegisterAttached("HtmlString", typeof(string), typeof(MyProperties), new PropertyMetadata("", OnHtmlStringChanged));

     // Getter and Setter
     public static string GetHtmlString(DependencyObject obj) { return (string)obj.GetValue(HtmlStringProperty); }
     public static void SetHtmlString(DependencyObject obj, string value) { obj.SetValue(HtmlStringProperty, value); }

     // Handler for property changes in the DataContext : set the WebView
     private static void OnHtmlStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     {
        WebView wv = d as WebView; 
        if (wv != null) 
        { 
            wv.NavigateToString((string)e.NewValue); 
        } 
     }
    }
}

假设您的DataContext字段称为CurrentHtmlString,则可以在XAML文件中使用此新WebView的HtmlString属性将其绑定,语法如下:

Supposing that your DataContext field is called CurrentHtmlString, then you can use this new WebView's HtmlString property in your XAML file to bind it, with a syntax like :

 <WebView local:MyProperties.HtmlString="{Binding CurrentHtmlString}"></WebView>

通常,您的XAML文件顶部已经有以下行:

Normally you already have the following line at the top of your XAML file :

xmlns:local="using:MYNAMESPACE"

您可以在Rob Caplan处找到更多解释: http://blogs.msdn.com/b/wsdevsol/archive/2013/09/26/binding-html-to-a-webview-with-attached-properties.aspx

You can find more explanation here from Rob Caplan : http://blogs.msdn.com/b/wsdevsol/archive/2013/09/26/binding-html-to-a-webview-with-attached-properties.aspx

这篇关于将html字符串内容绑定到xaml中的Webview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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