Xamarin navigate to page throws "Object reference not set to an instance of an object."

tim 200 Reputation points
2024-04-10T23:23:39.3666667+00:00

I'm trying to navigate and pass data to an edit page when I select a row.

I select a row in the checklistpage and what to pass that rows data to the treeinfopage. (has two points of entry 1 from menu and 1 from ChecklistPage)

the page structures are as follows:

treeInfoPage.xaml

treeInfoPage.xaml.cs

treeInfoPageModel.cs

checklistpageModel.cs

    private INavigationService _navigationService;

// not sure if this should be ChecklistpageModel or Checklistpage or Treeinfo...

    public void TreeInfoPageModel(INavigationService navigationService)

    {

        _navigationService = navigationService;           

    }

    public async void OnEditCommandAction(object SelectedObj)

    {          

        var treeInfoPage = new TreeInfoPage();

        treeInfoPage.BindingContext = SelectedObj;

     // everything work till the here , then the Object reference not set is thrown.

        await _navigationService.NavigateToAsync<TreeInfoPageModel>();

//

       /*tried the following, which in debug mode, will execute the TreeInfoPageModel code and Sector get set with show that the data is being passed but If I select the TreeInfoPage from the menu, the fields are empty, I assume that from the menu the data is cleared and the navigation is what is needed */

       // var pd2pm = new TreeInfoPageModel((CheckListItem)SelectedObj);

        return;

    }

TreeInfoPageModel.cs

public TreeInfoPageModel(CheckListItem data)

    {

        StatusMsg = "Ready";

        WorkTreeLocationItems = new ObservableCollection<WorkTreeLocationItem>();

        SaveLocationDataModel = new ButtonModel("Save Data", OnSaveLocationDataAction);

        Close_App_Clicked = new ButtonModel("Close App", CloseAppAction);

// prevents field from filling with 0 when entry from menu.

        if (data.TreeNumber > 0)

        {

            StatusMsg = data.Sector.ToString();

            Sector = data.Sector.ToString();

Thanks

Tim

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,362 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,173 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 76,386 Reputation points Microsoft Vendor
    2024-04-11T06:03:48.1366667+00:00

    Hello,

    Xamarin support will end on May 1, 2024, it's recommended that you migrate your Xamarin app to .NET MAUI. Please see Xamarin official support policy .

    =============Update==================

    You used Enterprise App Navigation, please refer to the following steps to make the navigation and fix errors.

    Step 1: please open MenuPageModel.cs , remove other content, just keep one constructor like following code.

    public class MenuPageModel : PageModelBase
    {
         public MenuPageModel() {
    
         
    
         }  
    }
    

    Step 2: Open MenuPage.xaml remove all of BindingContext= yourModel like following code.

    <?xml version="1.0" encoding="utf-8" ?>
    <TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                xmlns:d="http://xamarin.com/schemas/2014/forms/design"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
                android:TabbedPage.ToolbarPlacement="Bottom"
                mc:Ignorable="d"
                xmlns:pages="clr-namespace:MapleSugar.Pages"
                x:Class="MapleSugar.Pages.MenuPage">
        <TabbedPage.Children>
            <NavigationPage Title="Collection">
                <x:Arguments>
                    <pages:CollectionPage />
                </x:Arguments>
            </NavigationPage>
            <NavigationPage Title="Tree Location">
                <x:Arguments>
                    <pages:TreeInfoPage />
                </x:Arguments>
            </NavigationPage>
           <NavigationPage Title="Check List">
                <x:Arguments>
                    <pages:CheckListPage />
                </x:Arguments>
            </NavigationPage>
            <NavigationPage Title="Map Page">
                <x:Arguments>
                    <pages:MapPage />
                </x:Arguments>
            </NavigationPage>       
          <!--  <NavigationPage Title="File Picker">
                <x:Arguments>
                    <pages:FilePickerPage BindingContext="{Binding FilePickerPage}"/>
                </x:Arguments>
            </NavigationPage>
            -->
            <NavigationPage Title="File IO">
                <x:Arguments>
                    <pages:FileSystemPage />
                </x:Arguments>
            </NavigationPage>
    
    
       </TabbedPage.Children>
    </TabbedPage>
    

    Step 3: Open CheckListPage.xaml, add CheckListPageModel in the ContentPage's xml. As Note, please add pageModel for other pages like FileSystemPage , CollectionPage , TreeInfoPage CheckListPage .

    <ContentPage 
    ...
                 add this content
                 xmlns:local="clr-namespace:MapleSugar.PageModels"
    
    ...
                 x:Class="MapleSugar.Pages.CheckListPage">
    
    add page model here
    
        <ContentPage.BindingContext>
            <local:CheckListPageModel />
        </ContentPage.BindingContext>
    

    Step 4: open CheckListPageModel.cs, remove navigationService in constructor like following code.

    public CheckListPageModel()
      {
    
                  
    
          WorkTreeLocationItems = new ObservableCollection<WorkTreeLocationItem>();
    
          Load_Button_Clicked = new ButtonModel("Load Data", LoadCheckListAction);
    
           OnEditCommand = new Command(OnEditCommandAction);
    
          Close_App_Clicked = new ButtonModel("Close App", CloseAppAction);           
    
      }
    

    And use following code to make a Navigation and send data to TreeInfoPageModel

     public async void OnEditCommandAction(object SelectedObj)
      {
          CheckListItem checkListItem = SelectedObj as CheckListItem;
          // navigationService.PushAsync(new TreeInfoPage(checkListItem));      
    
    
         var navService = PageModelLocator.Resolve<INavigationService>();
    
    
    
         await navService.NavigateToAsync<TreeInfoPageModel>(checkListItem, true);
          return;
      }
    

    Step 5: In this TreeInfoPageModel.cs, please chanage the TreeInfoPageModel's constructor like following code and override InitializeAsync, you can get the navigated data by object navigationData

    /*  main code */
    public TreeInfoPageModel( )
    {
         StatusMsg = "Ready";
         WorkTreeLocationItems = new ObservableCollection<WorkTreeLocationItem>();
         SaveLocationDataModel = new ButtonModel("Save Data", OnSaveLocationDataAction);
         Close_App_Clicked = new ButtonModel("Close App", CloseAppAction);
    
    
    }
    
    
    public override Task InitializeAsync(object navigationData)
    {
         if (navigationData is WorkCollectedItem)
         {
             WorkCollectedItem workCollectedItem = navigationData as WorkCollectedItem;
             //  for testing.
    
    
            TreeNumber = workCollectedItem.TreeNumber.ToString();
         }
    
    
        if (navigationData is CheckListItem)
         {
             CheckListItem workCollectedItem = navigationData as CheckListItem;
    
             //  for testing.
    
    
            TreeNumber = workCollectedItem.TreeNumber.ToString();
         }
    
    
         return base.InitializeAsync(navigationData);
    }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  2. Muhammad Nomann 0 Reputation points
    2024-04-17T08:02:13.5166667+00:00

    I was having the same issue but you described it pretty well. Thanks alot!


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.