首页 > 解决方案 > 在 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文件中的上述事件,我如何将字符串的值传递cmdLineStringMainPage.xaml.cs文件?示例:我传递Hello World到命令行。该App.xaml.cs文件读取该参数。现在通过我的代码,我想将该Hello World值传递给MainPage.xaml.cs文件,以便可以将其分配给TextBlock.Text主窗口中的属性。

环境VS2019 - ver 16.5.5Windows 10 Pro - 1903

标签: c#uwpwindows-community-toolkituwp-navigation

解决方案


在 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);
}

有关导航的更多信息,您可以参考此文档


推荐阅读