如何在 UWP WebView 中设置硬编码 HTML

How to set hard coded HTML in UWP WebView

我有一些硬编码 html:

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

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

webView.HtmlSource = myHtml;

一般情况下,我们使用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