Share via

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 development | Windows App SDK
Developer technologies | XAML
Developer technologies | 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.

Developer technologies | C#
Developer technologies | 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.

{count} votes

Your answer

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