如何在onappear()方法导航?



我想避免将我的OnBoarding视图放在导航堆栈中以解决按下后退按钮的问题。在我的MainPage中,我检查OnBoarding是否应该出现。如果为真,我在OnAppearing方法中调用PushModalAsync方法。但应用程序崩溃,有以下例外:

Objective-C exception thrown.  Name: System.InvalidOperationException Reason: Window should have a UIWindow set. (System.InvalidOperationException)
at Microsoft.Maui.Controls.Window.get_NativeWindow()
at Microsoft.Maui.Controls.Platform.ModalNavigationManager.EndEditing()
at Microsoft.Maui.Controls.Platform.ModalNavigationManager.PushModalAsync(Page modal, Boolean animated)
at Microsoft.Maui.Controls.Window.NavigationImpl.OnPushModal(Page modal, Boolean animated)
at BytePesaApp.MainPage.OnAppearing() in MainPage.xaml.cs:line 18
at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_0(Object state)
at Foundation.NSAsyncSynchronizationContextDispatcher.Apply()

下面是代码实现:

public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
if (ShouldShowOnBoardingPage() == true)
{
await Navigation.PushModalAsync(new OnBoardingPage(), false);
}
}

private bool ShouldShowOnBoardingPage()
{
return VersionTracking.IsFirstLaunchEver;
}
}

听起来毛伊岛的导航状态不太好,直到onappear结束。像这样延迟导航:

Dispatcher.Dispatch(async() =>
await Navigation.PushModalAsync(new OnBoardingPage(), false);
);

此代码将排队,并将在onappear返回后运行。


一个替代是在登录过程中替换主页。
In app . example:

if (ShouldShowOnBoardingPage() == true)
MainPage = new OnBoardingPage();
else
MainPage = new MainPage();

当OnBoarding完成时:

Application.Current.MainPage = new MainPage();

如果可能的话,我更喜欢后一种方法。

OnAppearing()之后触发Loaded-Event;不幸的是,没有OnLoad()可以覆盖,所以您必须使用事件:

public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
this.Loaded += MainPage_Loaded;
}
protected async void MainPage_Loaded(object sender, EventArgs e)
{
if (ShouldShowOnBoardingPage() == true)
{
await Navigation.PushModalAsync(new OnBoardingPage(), false);
}
}
private bool ShouldShowOnBoardingPage()
{
return VersionTracking.IsFirstLaunchEver;
}
}

其中一个决定是使用task:

protected override async void OnAppearing()
{
base.OnAppearing();
if (ShouldShowOnBoardingPage() == true)
{
Task.Run(async () => 
{
await Navigation.PushModalAsync(new OnBoardingPage(), false);
});

}
}

相关内容

  • 没有找到相关文章

最新更新