System.NullReferenceException: 'Object reference not set to an instance of an object.' when navigating to page in WinUI
I am working with a WinUI project which is built based on the MVVM Toolkit template.
When I use NavigationService.NavigateTo(typeof(EmployeeViewModel).FullName!); to navigate to EmployeePage, the program crashes with the bug that System.NullReferenceException: 'Object reference not set to an instance of an object.' at this line:
"var navigated = _frame.Navigate(pageType, parameter);"
I have debugged the issue and confirmed that pageType and _frame is not null at runtime. Here is their values during debugging:
Here is the code of NavigateTo method:
public bool NavigateTo(string pageKey, object? parameter = null, bool clearNavigation = false)
{
var pageType = _pageService.GetPageType(pageKey);
if (_frame != null && (_frame.Content?.GetType() != pageType || (parameter != null && !parameter.Equals(_lastParameterUsed))))
{
_frame.Tag = clearNavigation;
var vmBeforeNavigation = _frame.GetPageViewModel();
var navigated = _frame.Navigate(pageType, parameter);
if (navigated)
{
_lastParameterUsed = parameter;
if (vmBeforeNavigation is INavigationAware navigationAware)
{
navigationAware.OnNavigatedFrom();
}
}
return navigated;
}
return false;
}
I would really appreciate it if you guys could tell me why does this bug occurs and how to fix this.
Thank you advance for your support!