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



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

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

我可以绑定WebViewSource属性来导航到URI,但我不知道如何在WebView中加载HTML内容。

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

显而易见的方法是从我的ViewModel中获得对WebView的引用,但我不知道如何做到这一点,这会破坏MVVM模式的分离。

有人能提出解决方案吗?

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();
}
}
<Page
x:Class="ReaderZero.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<WebView Source="{x:Bind Path=ViewModel.SelectedEntry.Uri, Mode=OneWay}" />
</Page>

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

对于这种情况,您可以参考将HTML绑定到具有附加属性的WebView博客,以生成类似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,并绑定Visibility with ToggleButtonIsChecked属性。这不会破坏MVVM模式的分离

最新更新