如何在UWP应用运行时执行保存在平铺中的命令?
问题描述:
我有一个应用程序,它在启动屏幕上用一个存储在磁贴中的特定命令固定辅助磁贴。如何在UWP应用运行时执行保存在平铺中的命令?
- 如果应用程序正在运行或在后台,我挖掘固定瓦,应用程序是无法获得从瓦的参数,因为中的MainPage的方法的OnNavigatedTo不叫。
- 如果我关闭/终止应用程序,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不为null时,不会调用MainPage.OnNavigatedTo。
我试着通过删除上面的if语句来解决问题,但是每次点击磁贴时都会实例化MainPage get。所以,如果我从应用程序列表中启动应用程序两次,然后点击平铺。
我希望tile在未运行时启动应用程序,并且在应用程序运行时执行其存储的命令,而不需要第二次实例化MainPage。
有避免这种情况的最佳实践方法吗? 如果我只是在App.xaml.cs处理瓷砖命令?:
//...
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.xaml.cs瓦片OnLaunched方法。
如果你想让你的MainPage接收参数,你必须添加一些特殊的逻辑。您可以通过检查TileId(除非您手动编辑应用程序清单,它将是“应用程序”),从而确定您是从次要磁贴启动的。然后,您可以确定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);
}
...
答
如果您在App
类重写此Application
方法:
protected override async void OnActivated(IActivatedEventArgs args)
...你应该被称为 - 至少这种方法适用于敬酒通知。 Application
有一大堆可覆盖的入口点。
(这OnNavigatedTo
方法是你谈论的页面有这样的方法?应用程序不)
谢谢你的提示,我会尝试这种方法。 我在谈论MainPage.OnNavigatedTo方法。那就是我放置瓷砖参数处理代码的地方,这就是当我点击一个瓷砖并且在后台应用程序时不会调用的地方。 MainPage决定参数如何处理,并负责进一步的操作。 – robcsi
啊,对。 'Page。如果页面已经打开,OnNavigatedTo方法将不会被调用; 'App'中的'On * Activated'方法中的一个几乎肯定是要走的路。 (有几个。) –