IoTBrowser,从 task/thread 浏览网页视图

IoTBrowser, navigate webview from task/thread

有一个网络视图:

<WebView x:Name="webView" Margin="0,10" Grid.RowSpan="3" LoadCompleted="webView_LoadCompleted"/>

还有一个基本的代码片段,它启动一个将侦听 azure 设备的任务。以下示例中缺少一些代码,假设设备是正常创建的。

问题是我想告诉 Webview 导航到某个网页,具体取决于收到的消息的内容。

问题是,。 "Window.Current" 为空,因此崩溃。

public App()
{
  Task.Run(ReceiveC2dAsync);
}

private async static Task ReceiveC2dAsync()
{
  while (true)
  {
    Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync();
    if(receivedMessage != null)
    {
      // Snip
      Task.Run(Navigate);
    }
  }
}

private async static Task Navigate()
{
  try
  {
    if(Window.Current.Content != null)
      ((Frame)Window.Current.Content).Navigate(typeof(MainPage), "http://www.google.com");
  }
  catch(Exception e)
  {
    Debug.WriteLine("{0} Exception caught.", e);
  }
}

在覆盖代码中:

protected override void OnLaunched(LaunchActivatedEventArgs e)

以下代码可用于在应用程序启动时导航到所需的网站:

Frame rootFrame = Window.Current.Content as Frame;
if(rootFrame == null) rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), "ms-appx-web:///help.html");

因此,此时 current 不为空。 如果我将 rootframe 保存为静态,并在稍后的任务中使用它,我会收到编组错误 - 基本上说明该对象被引用为编组到另一个线程。

我的 C# 知识是。我担心正在进行中。 到目前为止,我一直无法找到关于如何让 webview 响应内部任务的正确解释。可能吗?如果是,怎么做?

PS:初始示例代码来自:https://github.com/ms-iot/samples/tree/develop/IoTBrowser

The problem, is that I'd like to tell the Webview to navigate to a certain webpage

根据您的代码片段,您正在开发一个 UWP 应用程序。如果你想知道如何WebView导航到一个网站,你应该可以使用WebViewNavigate方法,例如:

webView.Navigate(new Uri("http://www.google.com"));

The following code can be used to navigate to a desired website when the application launches:

代码段默认在 OnLaunched navigate to one page by Frame. Frame control supports navigation to Page 个实例中,而不是网页中,您无法通过 Frame 导航到网站。您上面的代码片段只能让 rootFrame 导航到 MainPage,而不是 help.html。但是您可以在 MainPage 上获取 ms-appx-web:///help.html 参数并通过 MainPage 上的 WebView 导航到它。

I get a marshal error - basically stating the object is referenced to be marshaled to another thread.

如果你想在不同的线程中调用UIElement,你应该可以使用Core​Dispatcher,不能直接调用。

总而言之,我认为您真正想要做的是通过 WebView 从非 UI 线程导航到网站。例如:

await Task.Run(Navigate);
private async Task Navigate()
{        
    try
    {
        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
        {
            webView.Navigate(new Uri("http://www.google.com"));    
        });
    }
    catch (Exception e)
    {
        Debug.WriteLine("{0} Exception caught.", e);
    }
}