System.NullReferenceException: 'Object reference not set to an instance of an object.' when navigating to page in WinUI

LÊ CAO TUẤN VŨ 0 Reputation points
2024-11-23T09:39:11.4333333+00:00

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:User's image

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!

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
804 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,152 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
824 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.