How to set hard coded HTML in UWP WebView

℡╲_俬逩灬. 提交于 2020-01-25 07:31:05

问题


I have some hard coded html:

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

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

webView.HtmlSource = myHtml;

回答1:


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>

For more details, you can refer to Binding HTML to a WebView with Attached Properties.



来源:https://stackoverflow.com/questions/59537299/how-to-set-hard-coded-html-in-uwp-webview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!