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

时间:2016-01-22 12:48:47

标签: c# navigation windows-phone uwp

我有一个应用程序,它会在开始屏幕上固定辅助磁贴,并在磁贴中存储某个命令。

  1. 如果应用程序正在运行或处于后台,并且我点击固定磁贴,则应用程序无法从磁贴中获取参数,因为未调用MainPage的OnNavigatedTo方法。
  2. 如果我关闭/终止应用程序,则会调用OnNavigatedTo方法,因此我可以从磁贴中获取参数。
  3. 在第1点,未调用OnNavigatedTo,因为在App.xaml.cs中,只有在尚未将其设置为rootFrame的内容时才导航到MainPage:

    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不为null时,不会调用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);
                 }
             }
         }
    }
    

    由于

2 个答案:

答案 0 :(得分:3)

tile参数将传递给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);
    }

    ...

答案 1 :(得分:0)

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

protected override async void OnActivated(IActivatedEventArgs args)

...你应该被召唤 - 至少这种方法适用于吐司通知。 Application有一大堆可以覆盖的切入点。

(你在谈论哪种OnNavigatedTo方法?页面有这样的方法;应用程序没有?)