我使用Prism Template Pack创建了一个Prism Unity App,并为其添加了另一个View和ViewModel(OtherPage和OtherPageViewModel)。这是我的代码:
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("MainPage?title=Hello%20from%20Xamarin.Forms");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<MainPage>();
Container.RegisterTypeForNavigation<OtherPage>();
}
}
public class MainPageViewModel : BindableBase, INavigationAware
{
private INavigationService _navigationService;
private IPageDialogService _pageDialogService;
public DelegateCommand NavigateToOtherPageCommand { get; set; }
private string _title;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public MainPageViewModel(INavigationService navigationService,
IPageDialogService pageDialogService)
{
_navigationService = navigationService;
_pageDialogService = pageDialogService;
NavigateToOtherPageCommand = new DelegateCommand(async () => await NavigateToOtherPage());
}
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public async void OnNavigatedTo(NavigationParameters parameters)
{
if (parameters.ContainsKey("title"))
Title = (string)parameters["title"] + " and Prism";
await _pageDialogService.DisplayAlertAsync("Message", "Message for the user", "Ok");
}
private async Task NavigateToOtherPage()
{
await _navigationService.NavigateAsync("OtherPage");
}
}
public class OtherPageViewModel : BindableBase, INavigationAware
{
private IPageDialogService _pageDialogService;
public OtherPageViewModel(IPageDialogService pageDialogService)
{
_pageDialogService = pageDialogService;
}
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public async void OnNavigatedTo(NavigationParameters parameters)
{
await _pageDialogService.DisplayAlertAsync("Message", "Message for the user", "Ok");
}
}
我正在尝试使用IPageDialogService在MainPageViewModels的OnNavigatedTo方法中向用户显示消息,但不显示任何消息,也不会引发错误。
但是,如果我使用NavigateToOtherPageCommand从MainPage导航到OtherPage,则会正确显示该消息。为什么IPageDialogService不能在启动页面的OnNavigatedTo方法中工作(即MainPageViewModel)?它似乎在任何其他页面的OnNavigatedTo方法中工作正常(即OtherPageViewModel)。
答案 0 :(得分:2)
尝试使用await Task.Yield()
。有关此问题的详细信息,请参阅此链接:pageDialogService MainPage reference is always null inside OnNavigatedTo after app is launched