【问题标题】:How do I load html content into UWP WebView from a variable如何将 html 内容从变量加载到 UWP WebView
【发布时间】:2023-03-07 10:53:02
【问题描述】:

我有一个 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>

【问题讨论】:

  • 不是重复的 - 那是显示本地文件,这是来自变量的内容,这是完全不同的,除非你建议我每次需要显示内容时都创建临时文件!跨度>
  • 好的。但也许这是唯一的解决方案,我不知道。
  • 嗨@Mog0,您是否测试过以下解决方案。它对你有用吗?
  • 嗨@Nico Zhu,对不起,我还没有机会尝试它,但它看起来确实是我需要的。这是一个个人项目,主要是在周末进行,但我会尽快尝试。

标签: c# webview uwp uwp-xaml


【解决方案1】:

我知道有一个方法 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模式的分离

【讨论】:

  • 感谢@Nico,这似乎工作得很好。也非常感谢文档的链接,这样我就可以更好地理解代码,以防我需要对其进行调整或在其他地方执行此操作。很棒的答案,希望我能多投一票☺
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
相关资源
最近更新 更多