如何从变量将HTML内容加载到UWP WebView中

问题描述

我有一个UWP应用,其中的视图包含一个WebView。 在我的viewmodel中,我有两个变量,一个包含URI,另一个包含HTML内容

我需要能够导航到URI或显示HTML内容,具体取决于ToggleButton的状态。

我可以绑定Source的{​​{1}}属性以导航到URI,但是我不知道如何在WebView中加载HTML内容

我知道有一个方法WebView,但不知道如何从我的viewmodel调用它。我读过您应该从视图后面的代码调用它,但是我的视图看不到viewmodel中的内容

一种明显的方法是从我的viewmodel中获得对WebView.NavigatetoString(string)的引用,但是我不知道该怎么做,这破坏了MVVM模式的分离。

有人可以提出解决方案吗?

WebView
public class MainPageviewmodel : INotifyPropertyChanged
{
    // These properties all observable - notification omitted
    // for brevity
    public bool UseUri { get; set; }
    public string HtmlContent { get; set; }
    public Uri WebUri { get; set; }
}
public sealed partial class MainPage : Page
{
    public MainPageviewmodel viewmodel { get; }

    public MainPage()
    {
        this.InitializeComponent();

        viewmodel = new MainPageviewmodel();
    }
}

解决方法

我知道有一个方法WebView.NavigateToString(string),但是不知道如何从我的ViewModel调用它。我读过您应该从视图后面的代码中调用它,但是我的视图看不到ViewModel中的内容。

在这种情况下,您可以参考Binding HTML to a WebView with Attached Properties博客,使WebViewExtention如下所示。

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);
        }
    }
 }

用法

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

基于上面的内容,您可以制作两个WebViews并将“可见性”与ToggleButton IsChecked属性绑定。这不会破坏MVVM模式的分离