【问题标题】:Binding html string content to Webview in xaml将html字符串内容绑定到xaml中的Webview
【发布时间】:2016-03-09 18:08:35
【问题描述】:

我的 xaml 中有一个 webview,如下所示:

<WebView x:Name="WebView" />

而且,在我的代码隐藏中,我有一个名为“htmlcontent”的变量,其中包含如下所示的 html 字符串数据:

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

如何绑定这个 html 字符串并在 XAML 的 webview 组件中显示它的格式?

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

【问题讨论】:

标签: c# xaml webview


【解决方案1】:

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

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 属性来绑定它,语法如下:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-05
    • 2016-07-27
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2011-07-15
    相关资源
    最近更新 更多