【问题标题】:How to set hard coded HTML in UWP WebView如何在 UWP WebView 中设置硬编码 HTML
【发布时间】:2020-04-19 13:57:13
【问题描述】:

我有一些硬编码的 html:

string myHtml = "<html>some html</html>"

如何将其设置为我的 WebView 源?像这样的:

webView.HtmlSource = myHtml;

【问题讨论】:

    标签: webview uwp


    【解决方案1】:

    一般来说,我们使用WebView.NavigateToString(htmlstring);来加载和显示html字符串。对于 WebView 的来源,仅适用于 Uri 参数。但是您可以为 WebView 创建一个附加属性,如 HtmlSource,并在它更改时调用 NavigateToString 进行加载。

    public class MyWebViewExtention
    {
        public static readonly DependencyProperty HtmlSourceProperty =
               DependencyProperty.RegisterAttached("HtmlSource", typeof(string), typeof(MyWebViewExtention), new PropertyMetadata("", OnHtmlSourceChanged));
        public static string GetHtmlSource(DependencyObject obj) { return (string)obj.GetValue(HtmlSourceProperty); }
        public static void SetHtmlSource(DependencyObject obj, string value) { obj.SetValue(HtmlSourceProperty, value); }
        private static void OnHtmlSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            WebView webView = d as WebView;
            if (webView != null)
            {
                webView.NavigateToString((string)e.NewValue);
            }
        }
     }
    

    .xaml:

    <WebView x:Name="webView" local:MyWebViewExtention.HtmlSource="{x:Bind myHtml,Mode=OneWay}"></WebView>
    

    更多详情可以参考Binding HTML to a WebView with Attached Properties

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 2017-01-03
      • 2014-12-29
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多