c# - 在 UWP 应用中,读取命令行参数并将其从 App.xaml.cs 文件传递到 MainPage.xaml.cs
问题描述
我可以UWP
从 Windows 命令提示符或 PowerShell 启动我的应用程序。我也对如何读取传递给 UWP 应用程序的参数有了一些想法。但是,我找不到任何关于如何将这些参数从App.xaml.cs
文件传递到MainPage.xaml.cs
.
例如,您可以为您的 UWP 应用定义一个应用执行别名(如下所示),以便您可以轻松地从cmd
或启动它powershell
:
<Extensions>
<uap5:Extension
Category="windows.appExecutionAlias"
StartPage="index.html">
<uap5:AppExecutionAlias>
<uap5:ExecutionAlias Alias="MyApp.exe" />
</uap5:AppExecutionAlias>
</uap5:Extension>
</Extensions>
然后,您可以从OnActivated
事件中读取参数,如下所示:
async protected override void OnActivated(IActivatedEventArgs args)
{
switch (args.Kind)
{
case ActivationKind.CommandLineLaunch:
CommandLineActivatedEventArgs cmdLineArgs =
args as CommandLineActivatedEventArgs;
CommandLineActivationOperation operation = cmdLineArgs.Operation;
string cmdLineString = operation.Arguments;
string activationPath = operation.CurrentDirectoryPath;
……..
}
问题:从App.xaml.cs
文件中的上述事件,我如何将字符串的值传递cmdLineString
给MainPage.xaml.cs
文件?示例:我传递Hello World
到命令行。该App.xaml.cs
文件读取该参数。现在通过我的代码,我想将该Hello World
值传递给MainPage.xaml.cs
文件,以便可以将其分配给TextBlock.Text
主窗口中的属性。
环境:VS2019 - ver 16.5.5
,Windows 10 Pro - 1903
解决方案
在 UWP 中,参数通常通过导航在页面之间传递。
这段代码大致展示了OnActivated
方法的结构:
protected override void OnActivated(IActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
string commandParam = string.Empty;
switch (args.Kind)
{
case ActivationKind.CommandLineLaunch:
//get command parameter
break;
default:
//do other things...
break;
}
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage), commandParam);
}
// Ensure the current window is active
Window.Current.Activate();
}
拿到命令行参数后,最重要的是在这行代码中:
rootFrame.Navigate(typeof(MainPage), commandParam);
通过导航,我们可以将参数传递给MainPage
.
在此之后,我们需要接收MainPage
并处理它的参数:
MainPage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if(e.Parameter!=null && e.Parameter is string commandParam)
{
TestTextBlock.Text = commandParam;
}
base.OnNavigatedTo(e);
}
有关导航的更多信息,您可以参考此文档
推荐阅读
- python - 为什么pandas中的.columns方法没有括号()?
- excel - 网页抓取 Zerohedge
- docker - 为什么通过 ENTRYPOINT 和 tini 安装依赖项?
- python - 曲线拟合日志函数到数据时出错。TypeError:只有大小为 1 的数组可以转换为 Python 标量
- kotlin - 如何仅在kotlin中为每个地图键执行for循环?
- asp.net-mvc - 无法附加文件:FirstMVC.Models.EmployeeContext.mdf' 作为数据库'FirstMVC.Models.EmployeeContext'
- .net-core - MassTransit 和 RabbitMQ 中 ApiGateway-MicroService 通信模式的最佳设置
- shell - 主机名值的来源
- javascript - 启用“完整文档”的 MongoDB Atlas 仅返回更改的项目,而不是完整文档
- laravel - 如何在 Laravel Mix 中将 postcss-calc 设置为 false?