如何在 UWP WebView 中设置硬编码的 HTML [英] How to set hard coded HTML in UWP WebView

查看:26
本文介绍了如何在 UWP WebView 中设置硬编码的 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些硬编码的 html:

I have some hard coded html:

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

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

How can I set it as my WebView source? Something like this:

webView.HtmlSource = myHtml;

推荐答案

一般情况下,我们使用 WebView.NavigateToString(htmlstring); 来加载和显示 html 字符串.对于WebView的源码,只申请Uri参数.但是你可以为 WebView 创建一个像 HtmlSource 这样的附加属性,当它改变时调用 NavigateToString 来加载.

In general, we use WebView.NavigateToString(htmlstring); to load and display html string. For source of WebView, only apply for Uri parameters. But you can create an attached property like HtmlSource for WebView and when it changes to call NavigateToString to load.

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>

更多详情可以参考将 HTML 绑定到带有附加属性的 WebView.

这篇关于如何在 UWP WebView 中设置硬编码的 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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