.NET MAUI – Forget Me Not – Part 5

Building on the previous blog posts, here I’d like to illustrate how you can pass complex data from one page’s view model to another’s.

Let’s assume we’ve tapped on the Buddies Icon on the tab bar and were taken to the BuddyList:

If we tap on one of our buddies, in this case, Rodrigo, we should be taken to the details page for that buddy. We could pass along the buddy’s id, or we can pass the buddy object itself.

To pass the entire Buddy object, we will create a dictionary that will contain an identifying text as the key, and the SelectedBuddy as the value,

var navigationParameter = new Dictionary<string, object>
{
    {"SelectedBuddy", SelectedBuddy}
};

We can now pass that along to the details page using Shell navigation.

await Shell.Current.GoToAsync($"buddydetail", navigationParameter);

“buddydetail” is the name you gave the BuddyDetails page in the constructor in AppShell.xaml.cs

public AppShell()
{
     InitializeComponent();

     Routing.RegisterRoute("buddydetail", typeof(BuddyDetail));

This routing matches the key “buddydetail” to the BuddyDetail page. Returning to the Shell navigation above, we see navigationParameter is the second param for the GoToAsync call. That is, we pass along the dictionary that contains our object. (We can pass as many objects as we like, each as an entry in the dictionary).

Receiving the data

In the view model for the details page, BuddyDetailViewModel, we use the QueryProperty attribute to indicate the name of the property to assign the passed-in object to and the key in the dictionary associated with that object.

Looking a few paragraphs up we can see that the dictionary has an entry with the key “SelectedBuddy” which has a value of the SelectedBuddy object. Here we are going to retrieve that into a local property, also named SelectedBuddy

[ObservableObject]
[QueryProperty(nameof(SelectedBuddy), "SelectedBuddy")]
public partial class BuddyDetailViewModel

Let me review that briefly as it can get confusing. There is the name of the local property: SelectedBuddy. There is the first parameter in the QueryProperty attribute: nameof(SelectedBuddy). These are 1:1 — the nameof is pointing to a property in this (receiving) class. Finally, there is the second param in the attribute, the string “SelectedBuddy” which is the key into the dictionary whose value will be assigned to the SelectedBuddy property. Right? Piece of pie.

We want to bind to a number of the properties of the buddy we just passed in. First, we’ll create those properties:

[ObservableProperty] private string name;
[ObservableProperty] private string emailAddress;
[ObservableProperty] private string code;
[ObservableProperty] private string? phoneNumber;
[ObservableProperty] private InvitationStatus status;
[ObservableProperty] private DateTime buddySince;
[ObservableProperty] private string buddySinceString;
[ObservableProperty] private string mailingAddressLine1;
[ObservableProperty] private string mailingAddressLine2;
[ObservableProperty] private int id;

Now all we need to do is set those properties using the object that was passed in and assigned to our SelectedBuddy property

 private Buddy selectedBuddy;
 public Buddy SelectedBuddy
 {
     get => selectedBuddy;
     set
     {
         SetProperty(ref selectedBuddy, value);
         Name = value.Name;
         EmailAddress = value.EmailAddress;
         PhoneNumber = value.PhoneNumber;
         Status = value.Status;
         BuddySince = value.BuddySince;
         BuddySinceString = BuddySince.ToString("D");
         MailingAddressLine1 = value.MailingAddressLine1;
         MailingAddressLine2 = value.MailingAddressLine2;
         Id = value.Id;
     }
 }

We can now display the details of the selected buddy using data binding. in the XAML.

Notice that there are two buttons: one to see the occasions you’ve asked to be reminded about, with regard to this buddy (e.g., the buddy’s birthday). The second button will display the buddy’s preferences. Each of these is made easier by using a service, in this case BuddyService. But how do we access the methods in BuddyService? This will be the topic of the next blog entry: Dependency Injection in MAUI.

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.

21 Responses to .NET MAUI – Forget Me Not – Part 5

  1. money casino says:

    This website, you can discover lots of online slots from famous studios.
    Players can try out traditional machines as well as feature-packed games with high-quality visuals and bonus rounds.
    Whether you’re a beginner or an experienced player, there’s a game that fits your style.
    casino
    The games are ready to play round the clock and designed for desktop computers and smartphones alike.
    You don’t need to install anything, so you can get started without hassle.
    Site navigation is user-friendly, making it simple to browse the collection.
    Register now, and dive into the excitement of spinning reels!

  2. casino says:

    On this platform, you can discover a wide selection of casino slots from leading developers.
    Visitors can experience retro-style games as well as new-generation slots with stunning graphics and exciting features.
    Even if you’re new or a seasoned gamer, there’s something for everyone.
    casino
    The games are instantly accessible round the clock and compatible with laptops and tablets alike.
    No download is required, so you can get started without hassle.
    The interface is intuitive, making it simple to find your favorite slot.
    Register now, and enjoy the thrill of casino games!

  3. Seeking to connect with qualified contractors ready for temporary risky assignments.
    Require someone for a perilous assignment? Discover vetted laborers via this site for urgent risky work.
    github.com/gallars/hireahitman
    Our platform links employers with skilled workers prepared to accept hazardous short-term positions.
    Recruit background-checked freelancers to perform dangerous duties safely. Perfect when you need urgent assignments demanding safety-focused labor.

  4. Il nostro servizio consente l’assunzione di lavoratori per attività a rischio.
    Gli interessati possono scegliere candidati qualificati per incarichi occasionali.
    Ogni candidato vengono verificati con attenzione.
    assumere un killer
    Attraverso il portale è possibile leggere recensioni prima di assumere.
    La qualità è un nostro valore fondamentale.
    Sfogliate i profili oggi stesso per ottenere aiuto specializzato!

  5. Our service offers you the chance to connect with professionals for one-time risky projects.
    Visitors are able to efficiently request support for particular requirements.
    All workers are experienced in executing critical tasks.
    hire a hitman
    This service ensures private arrangements between clients and freelancers.
    When you need a quick solution, our service is the perfect place.
    Post your request and get matched with the right person instantly!

  6. Questo sito consente l’assunzione di lavoratori per compiti delicati.
    I clienti possono selezionare esperti affidabili per missioni singole.
    Ogni candidato vengono scelti secondo criteri di sicurezza.
    ordina omicidio
    Con il nostro aiuto è possibile consultare disponibilità prima della selezione.
    La sicurezza è un nostro valore fondamentale.
    Iniziate la ricerca oggi stesso per ottenere aiuto specializzato!

  7. Our service offers you the chance to hire experts for occasional risky tasks.
    Users can easily schedule support for specialized needs.
    All contractors are qualified in managing critical operations.
    hitman-assassin-killer.com
    The website guarantees private arrangements between requesters and workers.
    For those needing fast support, the site is the right choice.
    Create a job and connect with an expert now!

  8. Наша платформа — официальный интернет-бутик Боттега Венета с отправкой по всей России.
    На нашем сайте вы можете приобрести оригинальные товары Боттега Венета официально.
    Все товары подтверждены сертификатами от марки.
    bottega-official.ru
    Доставка осуществляется быстро в по всей территории России.
    Наш сайт предлагает удобную оплату и лёгкий возврат.
    Покупайте на официальном сайте Bottega Veneta, чтобы быть уверенным в качестве!

  9. Our service offers you the chance to get in touch with professionals for one-time high-risk missions.
    Clients may easily set up assistance for particular needs.
    All workers are trained in dealing with intense operations.
    hitman-assassin-killer.com
    This service offers safe arrangements between requesters and specialists.
    Whether you need a quick solution, this website is the right choice.
    List your task and match with an expert now!

  10. Оформление туристического полиса во время путешествия — это разумное решение для финансовой защиты отдыхающего.
    Документ гарантирует медицинские услуги в случае обострения болезни за границей.
    К тому же, документ может предусматривать покрытие расходов на возвращение домой.
    carbox30.ru
    Ряд стран требуют предоставление документа для въезда.
    Если нет страховки медицинские расходы могут стать дорогими.
    Получение сертификата заранее

  11. casino says:

    This website, you can discover a great variety of slot machines from leading developers.
    Users can enjoy retro-style games as well as feature-packed games with high-quality visuals and bonus rounds.
    If you’re just starting out or an experienced player, there’s always a slot to match your mood.
    casino games
    All slot machines are ready to play round the clock and compatible with laptops and mobile devices alike.
    No download is required, so you can start playing instantly.
    Site navigation is easy to use, making it quick to find your favorite slot.
    Sign up today, and discover the world of online slots!

  12. This section presents CD player radio alarm clocks crafted by trusted manufacturers.
    Browse through sleek CD units with PLL tuner and dual alarms.
    Most units include aux-in ports, USB charging, and backup batteries.
    Available products spans affordable clocks to premium refurbished units.
    cd clock radio
    Every model include snooze buttons, night modes, and bright LED displays.
    Buy now using online retailers with fast shipping.
    Choose the perfect clock-radio-CD setup for office convenience.

  13. DavidTwelt says:

    This website offers off-road vehicle rentals across the island.
    Anyone can easily book a vehicle for adventure.
    If you’re looking to discover coastal trails, a buggy is the ideal way to do it.
    https://www.behance.net/buggycrete
    Each buggy are well-maintained and can be rented for full-day plans.
    Through our service is user-friendly and comes with great support.
    Start your journey and experience Crete like never before.

  14. Jamescrumn says:

    The digital drugstore features a broad selection of health products for budget-friendly costs.
    Shoppers will encounter all types of medicines for all health requirements.
    We work hard to offer trusted brands without breaking the bank.
    Speedy and secure shipping guarantees that your order arrives on time.
    Experience the convenience of ordering medications online on our platform.
    what is a generic drug

  15. MichaelVilla says:

    It’s alarming to realize that over 60% of people taking prescriptions experience serious medication errors because of poor understanding?

    Your wellbeing is your most valuable asset. All treatment options you consider significantly affects your body’s functionality. Being informed about medical treatments is absolutely essential for optimal health outcomes.
    Your health isn’t just about swallowing medications. Each drug affects your body’s chemistry in potentially dangerous ways.

    Remember these critical facts:
    1. Combining medications can cause health emergencies
    2. Seemingly harmless allergy medicines have strict usage limits
    3. Self-adjusting treatment reduces effectiveness

    For your safety, always:
    ✓ Research combinations via medical databases
    ✓ Review guidelines in detail prior to using any medication
    ✓ Consult your doctor about potential side effects

    ___________________________________
    For reliable medication guidance, visit:
    https://vocus.cc/user/67faa75afd89780001e0079b

  16. casino slots says:

    Here, you can discover a great variety of slot machines from leading developers.
    Players can enjoy traditional machines as well as new-generation slots with vivid animation and interactive gameplay.
    Whether you’re a beginner or a seasoned gamer, there’s a game that fits your style.
    money casino
    Each title are ready to play anytime and designed for laptops and smartphones alike.
    All games run in your browser, so you can get started without hassle.
    The interface is easy to use, making it simple to explore new games.
    Register now, and dive into the thrill of casino games!

  17. Dustinser says:

    Traditional timepieces will always remain relevant.
    They represent engineering excellence and showcase a mechanical beauty that digital devices simply fail to offer.
    These watches is powered by precision mechanics, making it both reliable and elegant.
    Collectors admire the intricate construction.
    https://trackrecord.id/read-blog/10732
    Wearing a mechanical watch is not just about utility, but about honoring history.
    Their styles are everlasting, often passed from lifetime to legacy.
    To sum up, mechanical watches will never go out of style.

  18. money casino says:

    Here, you can find a wide selection of casino slots from leading developers.
    Visitors can try out classic slots as well as modern video slots with stunning graphics and exciting features.
    If you’re just starting out or a seasoned gamer, there’s always a slot to match your mood.
    play casino
    All slot machines are available anytime and designed for desktop computers and tablets alike.
    You don’t need to install anything, so you can start playing instantly.
    Platform layout is user-friendly, making it convenient to find your favorite slot.
    Join the fun, and dive into the excitement of spinning reels!

  19. Buy Proxies says:

    Its like you learn my thoughts! You appear to grasp a lot approximately this, such as you wrote the guide in it or something. I think that you just could do with some to power the message house a little bit, however other than that, this is magnificent blog. An excellent read. I will definitely be back.

  20. This is very interesting, You’re a very skilled blogger. I have joined your feed and look forward to seeking more of your magnificent post. Also, I have shared your website in my social networks!

Leave a Reply

Your email address will not be published. Required fields are marked *