如何在 运行 时使用 UWP 应用程序执行保存在磁贴中的命令?

How to execute command saved in tile with an UWP app while it's running?

我有一个应用程序可以将辅助磁贴固定在开始屏幕上,磁贴中存储了特定命令。

  1. 如果应用程序 运行 或在后台,并且我点击固定的图块,应用程序无法从图块中获取参数,因为未调用 MainPage 的 OnNavigatedTo 方法。
  2. 如果我 close/terminate 应用程序,调用 OnNavigatedTo 方法,因此我可以从磁贴中获取参数。

在第 1 点未调用 OnNavigatedTo,因为在 App.xaml.cs 中导航到 MainPage 仅当它尚未设置为 rootFrame 的内容时:

if (rootFrame.Content == null)
{
     // When the navigation stack isn't restored navigate to the first page,
     // configuring the new page by passing required information as a navigation
    // parameter
    rootFrame.Navigate(typeof(Views.MainPage), e.Arguments);
}

因此,当 rootFrame.Content 不为空时,不会调用 MainPage.OnNavigatedTo。

我尝试通过删除上面的 if 语句来解决问题,但是每次点击磁贴时都会实例化 MainPage。所以,如果我从应用程序列表启动应用程序然后点击磁贴两次。

我希望磁贴在非 运行 时启动应用程序,并在应用程序 运行 时执行其存储的命令,而无需再次实例化 MainPage。

是否有避免这种情况的最佳实践方法? 我应该只处理 App.xaml.cs 中的 tile 命令吗?:

//...
else
{
    if (e.PreviousExecutionState == ApplicationExecutionState.Running || e.PreviousExecutionState == ApplicationExecutionState.Suspended)
    {
         var mainPage = rootFrame.Content as Views.MainPage;
         if (mainPage != null)
         {
             string command = e.Arguments;
             if (!String.IsNullOrWhiteSpace(command) && command.Equals(Utils.DefaultTileCommand))
             {
                  await mainPage.HandleCommand(command);
             }
         }
     }
}

谢谢

如果您在 App class 中覆盖此 Application 方法:

protected override async void OnActivated(IActivatedEventArgs args)

...你应该被调用——至少这种方法适用于 toast 通知。 Application 有一大堆可覆盖的入口点。

(你说的是哪个 OnNavigatedTo 方法?页面有这样的方法;应用程序没有?)

磁贴参数已传递给您的 App.xaml.cs OnLaunched 方法。

如果您希望 MainPage 接收参数,则必须添加一些特殊逻辑。您可以通过检查 TileId(它将是 "App",除非您手动编辑了您的应用程序清单)来确定您是从辅助磁贴启动的。然后您可以确定 MainPage 当前是否显示,如果显示,则调用您在 MainPage 上添加的方法以将参数传递给当前实例。

这是代码...

protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
    ...

    if (rootFrame.Content == null)
    {
        // When the navigation stack isn't restored navigate to the first page,
        // configuring the new page by passing required information as a navigation
        // parameter
        rootFrame.Navigate(typeof(Views.MainPage), e.Arguments);
    }

    // If launched from secondary tile and MainPage already loaded
    else if (!e.TileId.Equals("App") && rootFrame.Content is MainPage)
    {
        // Add a method like this on your MainPage class
        (rootFrame.Content as MainPage).InitializeFromSecondaryTile(e.Arguments);
    }

    ...