How do you pass parameters in MAUI without using a ViewModel?

Viewed 78

I have this on one page

        await Shell.Current.GoToAsync(nameof(Pages.StartPage), true, new Dictionary<string, object>
        {
            { "LoginData", result }
        });

result is an object/class

In my Pages.StartPage I want to get that object. I have tried using [QueryProperty... but that always returns a null. E.g.

[QueryProperty(nameof(GetLoginData), "LoginData")]
public partial class StartPage : ContentPage

....

private JsonApiResult GetLoginData { set { _loginData = value; }  }

I've just started using MAUI and I am converting an app from Xamarin to MAUI. The pages I have built take care of themselves so I don't want to use viewmodels, I just need a value from that passed-in object for the page to do its stuff. I don't want to have to rewrite all my pages unless there is no other way

Any help would be much appreciated. I've watched loads of videos on this and I can't make it work, what am I missing?

UPDATE

I should add that to make matters more complex for myself, I am also using Dependency Injection (DI)

2 Answers

here it comes an example!

Main page .xaml:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MauiApp1.MainPage">

<ScrollView>
    <VerticalStackLayout
        Spacing="25"
        Padding="30,0"
        VerticalOptions="Center">
        <Button
            x:Name="CounterBtn"
            Text="Click me"
            SemanticProperties.Hint="Counts the number of times you click"
            Clicked="OnCounterClicked"
            HorizontalOptions="Center" />

    </VerticalStackLayout>
</ScrollView>

On main page .cs:

public MainPage()
{
    InitializeComponent();
}

private async void OnCounterClicked(object sender, EventArgs e)
{
    List<Student> myStudentsList = new List<Student>
    {
        new Student {Name="Carlos",Course="IT",Age=18},
        new Student {Name="Juan",Course="IT",Age=19},
        new Student {Name="Leandro",Course="IT",Age=20}
    };

    await Navigation.PushAsync(new PageWithStudentsList(myStudentsList));
    
}

PageWithStudentsList .cs :

public partial class PageWithStudentsList : ContentPage
{
    public PageWithStudentsList(List<Student> students)
    {
        Console.WriteLine(students);
        InitializeComponent();
    }
}

And you dont need to use viewmodel!

EDIT: in case you need another example with SHELL NAVIGATION, here is a microsoft example in their docs! Hope it helps!

private JsonApiResult _loginData;
public JsonApiResult LoginGetData { 
    get  => _loginData; 
    set { _loginData = value; } 
}

It seems this was the solution though I can't see why. I'll dig into it another time but right now its working so I can crack on

Related