[英]Reaching MainPage.Xaml.cs click handler functions from App.Xaml.cs in windows phone 8
[英]In UWP App, read command line arguments and pass it from App.xaml.cs file to the MainPage.xaml.cs
我可以從 windows 命令提示符或 PowerShell 啟動我的UWP
應用程序。 我對如何閱讀傳遞給 UWP 應用程序的 arguments 也有了一些想法。 但是,我找不到任何關於如何將那些 arguments 從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
事件中讀取 arguments,如下所示:
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
文件,這樣我就可以將它分配給主 window 中的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
中接收參數並進行處理:
主頁.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if(e.Parameter!=null && e.Parameter is string commandParam)
{
TestTextBlock.Text = commandParam;
}
base.OnNavigatedTo(e);
}
有關導航的更多信息,您可以參考此文檔
在App.xaml.cs
中定義一個變量
sealed partial class App : Application
{
public string cmdLineArgs;
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
..........
}
然后在OnActivated
事件中設置cmdLineArgs
的值。
然后你可以在項目的任何地方使用cmdLineArgs
string args = (Application.Current as App).cmdLineArgs;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.