在 OnNavigatedTo 之后做代码 [英] Do code after OnNavigatedTo
问题描述
我有代码从其他页面获取 IdUsers
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;
}
MessageBox 始终为 Null.我希望 MessageBox 在 OnNavigationTo 之后显示IdUsers"(不要将 MessageBox 放在OnNavigationTo"中).
The MessageBox Alway be Null. I Want to MessageBox Show the "IdUsers" after OnNavigationTo (Do not put the MessageBox IN "OnNavigationTo").
我该怎么做?
推荐答案
您不应该在 OnNavigatedTo 中使用 MessageBoxes,因为如果用户不按下按钮,您的应用程序将崩溃,因为框架认为导航失败.构造函数中的消息框同样糟糕.
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.
我可以想到两个选项(我将 #1 用于这类事情):
I can think of two options (I use #1 for these sorts of things):
在
Loaded
事件中显示 MessageBox.但要小心它可以发射不止一次.在构造函数中,您可以为 Loaded 事件添加处理程序,然后在处理程序中与处理程序分离,以便仅调用一次.
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.
在 MessageBox.Show
调用周围使用 Dispatcher.BeginInvoke
,这样它就不会阻塞导航.这可能仍会阻塞 Dispatcher 线程.如果你真的想走这条路,你可以使用 ThreadPool.QueueUserWorkItem
或 TPL 任务.
Use Dispatcher.BeginInvoke
around the MessageBox.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 use ThreadPool.QueueUserWorkItem
or a TPL Task.
我也使用 OnLayoutUpdated
代替 Loaded
事件,但我不记得确切原因:) 看起来可能是页面没有t 尚未显示在 Loaded
中,并且已在其他事件中显示.
I also have used OnLayoutUpdated
in place of the Loaded
event but I can't remember exactly why :) It seems like it might have been that the page hasn't yet displayed in Loaded
and it has in the other event.
这篇关于在 OnNavigatedTo 之后做代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!