I Have Code get IdUsers From Other Page
String IdUsers;
public Main_Wallets_Page()
{
InitializeComponent();
MessageBox.Show(IdUsers);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
String Id;
if (NavigationContext.QueryString.TryGetValue("IdUsers", out Id))
IdUsers = Id;
}
The MessageBox Alway be Null. I Want to MessageBox Show the "IdUsers" after OnNavigationTo (Do not put the MessageBox IN "OnNavigationTo").
How can i do it ?
You shouldn't use MessageBoxes in OnNavigatedTo because if the user does not press a button your app will crash since the framework thinks that navigation has failed. MessageBoxes in the constructor are equally as bad.
I can think of two options (I use #1 for these sorts of things):
Show the MessageBox in the
Loaded
event. But be careful it can be fired more than once. In the constructor you might add the handler for the Loaded event and then in the handler you'd detach from the handler so that it is called only once.Use
Dispatcher.BeginInvoke
around theMessageBox.Show
call so that it does not block navigation. That might still block the Dispatcher thread. If you really wanted to go this route you could useThreadPool.QueueUserWorkItem
or a TPL Task.I also have used
OnLayoutUpdated
in place of theLoaded
event but I can't remember exactly why :) It seems like it might have been that the page hasn't yet displayed inLoaded
and it has in the other event.DO NOT place
MessageBox
intoOnNavigatedTo
event. Try to create an empty project withMainPage
andPage2
. Place button onMainPage
to navigate toPage2
. InPage2
placeMessageBox
inOnNavigatedTo
event. Then everythig will work fine if you Start Debugging from VS. BUT if you deploy and run it you will see that when you navigate toPage2
you seeMessageBox
. Then don't do anything, just wait for about 15 sec.MessageBox
will react asCanceled
and APPLICATION WILL BE CRASHED! without any navigation toPage2
orMainPage
. The same thing happens if you useDispatcher.BeginInvoke
around theMessageBox.Show
. I assume thatOnNavigatedTo
event has a timeout which works only when app is deployed. So you should run yourMessageBox
when Navigation is competed. Everything works if you doNote: If you have some code in
OnNavigatedTo
run above code at the end ofOnNavigatedTo
.I liked what Austin Thompson(upvote) has adviced with
ThreadPool.QueueUserWorkItem
. But note that with this approach you need to place MessageBox inside theDispatcher.BeginInvoke
otherwise you will receive cross-thread exception. So the code is the followingIf this value was initialized, you can store it in application isolated storage. Then, when constructor is called, you can read it from there. In this case value of user ID will be initialized and MessageBox won't show you NULL.