Learning .NET MAUI – Part 11

This one should be short. We’re going to take a look at passing values when navigating.

Passing in values requires that you pass a Dictionary, where the key is an arbitrary string and the object is the value you are passing

 [ICommand]
 async Task GoToZipCodeDetailsAsync()
 {

     Result result = new Result
     {
         zip = "01720",
         city = "Acton",
         state = "MA"
     };

     
     try
     {
          await Shell.Current.GoToAsync($"ZipCodeDetailsPage", true,
             new Dictionary<string, object>
         {
                 
             { nameof(Result), result }
         });               
     }
     catch(Exception ex)
     {
         Debug.WriteLine(ex.Message);
         await Shell.Current.DisplayAlert("Unable to go to Details page!", ex.Message, "OK");
     }
 }

You would normally pass the Result object into GoToZipCodeDetailsAsync, but here I’m creating it on the fly for demonstration purposes.

ZipCodeDetailsPage is the page we are navigating to. true means we do want animation on the page change and the Dictionary contains a key and a value, in this case the Results collection.

To receive this in the called page, go to the ZipCodeDetailsViewModel and add this to the top (before the class name:

[QueryProperty(nameof(Result), “Result”)]

The first value (nameof(Result) will signal the name of the property, the second will be the value for that property (Result) You want to match this with a property in the class which you do just by declaring the property:

[ObservableProperty]
Result result;

We are now in a position to bind to that property

<VerticalStackLayout>
    <Label
        HorizontalOptions="Center"
        Text="Welcome to .NET MAUI!"/>
    <VerticalStackLayout>
        <Label Text="You made it to the details page!" />
        <Label Text="{Binding Result.city}" />
        <Label Text="{Binding Result.state}" />
        <Label Text="{Binding Result.zip}" />
    </VerticalStackLayout>
</VerticalStackLayout>

That’s really all there is to it.

The source code is here

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Essentials and tagged , . Bookmark the permalink.