.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.

Unknown's avatar

About Jesse Liberty

** Note ** Jesse is currently looking for a new position. You can learn more about him at https://jesseliberty.bio Thank you. 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, is now available wherever you buy your books. Liberty was a Team Lead and Senior Software Engineer for various corporations, 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 13 year Microsoft MVP.
This entry was posted in Essentials and tagged , , . Bookmark the permalink.

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

  1. shib price's avatar shib price says:

    I personally find that i’ve been using it for since launch for portfolio tracking, and the trustworthy service stands out. The dashboard gives a complete view of my holdings.

  2. The staking tools are reliable uptime and easy onboarding.

  3. I’ve been using it for several months for using the bridge, and the low fees stands out.

  4. I was skeptical, but after a week of portfolio tracking, the quick deposits convinced me.

  5. quq price's avatar quq price says:

    The providing liquidity process is simple and the accurate charts makes it even better. Definitely recommend to anyone in crypto.

  6. togel4d's avatar togel4d says:

    The trading tools are stable performance and robust security.

  7. I personally find that the best choice I made for portfolio tracking. Smooth and scalable features.

  8. nada market's avatar nada market says:

    The cross-chain transfers tools are seamless withdrawals and low fees.

  9. I’ve been using it for since launch for exploring governance, and the robust security stands out.

  10. shib price's avatar shib price says:

    The fiat on-ramp tools are fast transactions and trustworthy service.

  11. buy aster's avatar buy aster says:

    The interface is useful analytics, and I enjoy using the API here.

  12. I’ve been using it for a year for fiat on-ramp, and the robust security stands out. The updates are frequent and clear.

  13. Taylor here — I’ve tried learning crypto basics and the stable performance impressed me. Great for cross-chain swaps with minimal slippage.

  14. Charlie here — I’ve tried providing liquidity and the stable performance impressed me. The dashboard gives a complete view of my holdings.

  15. I personally find that the using the bridge process is simple and the reliable uptime makes it even better.

  16. Davidmeela's avatar Davidmeela says:

    Актуальное медоборудование играет важную часть в лечении и поддержке пациентов.
    Клиники всё чаще используют инновационную системы.
    Это обеспечивает специалистам проводить точные оценки.
    Актуальные приборы гарантируют надёжность и для больных, и для медиков.
    https://microsecondsconsulting.com/showthread.php?tid=705
    Развитие высоких технологий ускоряет качественное оздоровление.
    Многие устройства содержат опции для глубокого наблюдения состояния здоровья.
    Врачи могут оперативно реагировать, основываясь на показателях аппаратуры.
    Таким образом, инновационное техническое оснащение усиливает качество медицины.

  17. udintogel's avatar udintogel says:

    I personally find that i was skeptical, but after recently of using the bridge, the responsive team convinced me. My withdrawals were always smooth.

  18. I personally find that i switched from another service because of the fast transactions and low fees.

  19. togel4d's avatar togel4d says:

    I’ve been active for since launch, mostly for portfolio tracking, and it’s always clear transparency. The updates are frequent and clear.

  20. udintogel's avatar udintogel says:

    I trust this platform — withdrawals are stable performance and reliable. The updates are frequent and clear.

  21. inatogel's avatar inatogel says:

    I value the robust security and scalable features. This site is reliable. The dashboard gives a complete view of my holdings.

  22. SpiritSwap's avatar SpiritSwap says:

    I personally find that the interface is fast transactions, and I enjoy trading here. Charts are accurate and load instantly.

  23. KennethCom's avatar KennethCom says:

    Поиск остеопата — серьёзный этап на пути к реабилитации.
    Для начала стоит понять свои проблемы и ожидания от лечения у остеопата.
    Необходимо изучить образование и стаж выбранного остеопата.
    Комментарии клиентов помогут сформировать обоснованный выбор.
    https://rnd24.su/mesto/ozdorovitelnyy-centr-osteodok
    Также следует проверить методы, которыми оперирует специалист.
    Первая сессия позволяет почувствовать, насколько комфортно вам общение и подход доктора.
    Не забудьте проанализировать тарифы и условия сотрудничества (например, онлайн).
    Правильный выбор специалиста позволит сделать эффективнее процесс восстановления.

  24. AndrewVoics's avatar AndrewVoics says:

    When engaging in online gaming, it is important to define boundaries on your activity.
    Responsible gaming means managing your time and funds.
    Always be aware to see it as a hobby rather than a way to earn money.
    Apply the self-control features many platforms include to help you remain balanced.
    It’s recommended to pause regularly and assess your gaming habits.
    https://forum.sudden-strike-alliance.fr/viewtopic.php?t=5730
    Seek support or advice if you notice problems with your play.
    Sharing your gaming limits with friends or family can increase your self-awareness.
    With balanced gaming, you benefit from i-gaming while protecting your well-being.

  25. AndrewVoics's avatar AndrewVoics says:

    While playing internet gaming, it is essential to define boundaries on your activity.
    Responsible gaming means keeping track of your time and spending.
    Always make sure to see it as a hobby rather than a way to earn money.
    Take advantage of the safety features many platforms include to help you remain balanced.
    It’s recommended to pause regularly and assess your gaming habits.
    https://connect.garmin.com/modern/profile/54544b75-eb54-41d9-bcf9-43746f24de14
    Ask for support or advice if you feel overwhelmed with your play.
    Discussing your gaming limits with friends or family can boost your self-awareness.
    Through practicing balanced gaming, you get i-gaming while protecting your well-being.

  26. RobertGix's avatar RobertGix says:

    Отечественная мода выделяется самобытностью и разнообразной традицией.
    Современные дизайнеры опираются в традиционных узорах, создавая оригинальные модели.
    В показах всё чаще представлены необычные решения цветов.
    Отечественные дизайнеры развивают устойчивый подход к производству одежды.
    tatyana kochnova atelier
    Потребители всё больше следит за оригинальные бренды из России.
    Платформы о моде рассказывают о актуальных тенденциях и создателях.
    Начинающие бренды обретают известность как в России, так и за пределами страны.
    В итоге модная сцена успешно развиваться, объединяя традиции и современность.

  27. WilliamDiz's avatar WilliamDiz says:

    На этом сайте собрана интересная и практичная информация по разным темам.
    Читатели могут найти решения на актуальные темы.
    Статьи размещаются регулярно, чтобы вы каждый могли читать актуальную подборку.
    Интуитивная навигация сайта помогает быстро отыскать нужные страницы.
    http://ooptsao.ru/
    Разнообразие рубрикаторов делает ресурс интересным для разных посетителей.
    Каждый сможет найти материалы, которые интересуют именно ему.
    Присутствие понятных рекомендаций делает сайт особенно ценным.
    Таким образом, площадка — это надёжный проводник полезной информации для любого пользователей.

  28. ErnieWesee's avatar ErnieWesee says:

    Подбор консультанта — серьёзный процесс на пути к улучшению психологического здоровья.
    Прежде всего стоит понять свои цели и ожидания от сотрудничества с психологом.
    Хорошо изучить подготовку и опыт специалиста.
    Комментарии других обратившихся могут поспособствовать сделать выбор более осознанным.
    https://raymondglqu63063.wikirecognition.com/1724590/%D0%92%D1%80%D0%B0%D1%87_%D0%B4%D0%B5%D1%82%D1%81%D0%BA%D0%B8%D0%B9_%D0%BF%D1%81%D0%B8%D1%85%D0%B8%D0%B0%D1%82%D1%80_%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D1%8B_%D0%A6%D0%B5%D0%BD%D1%82%D1%80_%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B3%D0%BE_%D0%B7%D0%B4%D0%BE%D1%80%D0%BE%D0%B2%D1%8C%D1%8F_%D0%AD%D0%BC%D0%BF%D0%B0%D1%82%D0%B8%D1%8F
    Также следует учитывать подходы, которыми оперирует консультант.
    Первая встреча помогает оценить, насколько есть доверие общения.
    Важно учитывать стоимость и способ приёма (например, онлайн).
    Правильный выбор психолога способен улучшить личный рост.

  29. Anyswap's avatar Anyswap says:

    I’ve been using it for a week for trading, and the fast transactions stands out.

  30. danatoto's avatar danatoto says:

    Thanks for making this topic easy to grasp.

  31. AlvinGuets's avatar AlvinGuets says:

    Приобретение профессиональной техники — ответственный шаг в развитии косметологического кабинета.
    Прежде всего стоит уточнить цели и направления, которые вы планируете оказывать.
    Полезно изучить разрешения и качество выбранного аппарата.
    Комментарии прошлых специалистов помогут сделать обоснованный решение.
    beautyinstrument.ru
    Также необходимо обратить внимание на многофункциональность и удобство использования.
    Первая оценка оборудования помогает понять качество работы.
    Стоит также проанализировать цены и гарантийные условия.
    Грамотный выбор техники позволит улучшить уровень услуг.

  32. bos88's avatar bos88 says:

    Very interesting and easy to follow.

  33. inatogel's avatar inatogel says:

    Wonderful content, I learned a lot today.

  34. togelup's avatar togelup says:

    Your blog posts are always top-quality.

  35. Bk8's avatar Bk8 says:

    This article cleared up my doubts completely.

  36. ateliere de stimulare prin arta Constanta

  37. https://psihologpascani.ro/'s avatar https://psihologpascani.ro/ says:

    evaluare psihologica Pascani

  38. JamesMaync's avatar JamesMaync says:

    Поиск консультанта — важный процесс на пути к поддержанию эмоционального здоровья.
    Прежде всего стоит понять свои задачи и ожидания от консультации с психологом.
    Полезно проверить квалификацию и практику психолога.
    Отзывы других пациентов могут поспособствовать сделать выбор более обоснованным.
    Также следует учитывать подходы, которыми работает специалист.
    https://getlatestwallpapers.com/%D0%B2%D1%80%D0%B0%D1%87-%D0%BF%D1%81%D0%B8%D1%85%D0%B8%D0%B0%D1%82%D1%80-%D0%B8%D0%BD%D0%B4%D0%B8%D0%B2%D0%B8%D0%B4%D1%83%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9-%D0%BF%D0%BE%D0%B4%D1%85%D0%BE%D0%B4/
    Стартовая встреча поможет понять, насколько подходит стиль общения.
    Необходимо осознавать тариф и способ работы (например, онлайн).
    Осознанный выбор специалиста поможет сделать эффективнее личный рост.

  39. Scottnig's avatar Scottnig says:

    Поиск консультанта — важный процесс на пути к поддержанию эмоционального здоровья.
    Для начала стоит определить свои цели и запросы от консультации с психологом.
    Важно проверить подготовку и опыт консультанта.
    Рекомендации прошлых клиентов могут поспособствовать сделать решение более обоснованным.
    Также следует учитывать подходы, которыми пользуется специалист.
    https://jiwaku88vip3.com/%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD-%D0%BF%D1%81%D0%B8%D1%85%D0%B8%D0%B0%D1%82%D1%80-%D0%BA%D0%BE%D0%BD%D1%81%D1%83%D0%BB%D1%8C%D1%82%D0%B0%D1%86%D0%B8%D0%B8-%D0%B4%D0%BB%D1%8F-%D0%B2%D0%B0%D1%88/
    Стартовая встреча поможет понять, насколько вам комфортно общения.
    Следует осознавать стоимость и режим работы (например, очно).
    Осознанный выбор психолога поможет сделать эффективнее движение к целям.

  40. Scottnig's avatar Scottnig says:

    Выбор специалиста — ответственный шаг на пути к улучшению эмоционального здоровья.
    Прежде всего стоит уточнить свои цели и запросы от сотрудничества с экспертом.
    Полезно изучить образование и опыт консультанта.
    Рекомендации прошлых пациентов могут поспособствовать сделать выбор более уверенным.
    Также следует учитывать техники, которыми оперирует психолог.
    https://rmenjoy-mail.com/%D0%BA%D0%BE%D0%B3%D0%B4%D0%B0-%D0%BD%D1%83%D0%B6%D0%BD%D0%BE-%D0%BE%D0%B1%D1%80%D0%B0%D1%89%D0%B0%D1%82%D1%8C%D1%81%D1%8F-%D0%BA-%D0%B2%D1%80%D0%B0%D1%87%D1%83-%D0%BF%D1%81%D0%B8%D1%85%D0%B8%D0%B0/
    Стартовая встреча поможет почувствовать, насколько вам комфортно общения.
    Важно учитывать стоимость и режим приёма (например, удалённо).
    Осознанный выбор специалиста способен сделать эффективнее личный рост.

  41. you’re really a just right webmaster. The website loading pace is amazing. It seems that you are doing any unique trick. Moreover, The contents are masterwork. you have performed a magnificent process in this matter!

  42. Danielerubs's avatar Danielerubs says:

    Поиск специалиста — серьёзный процесс на пути к улучшению эмоционального здоровья.
    Для начала стоит определить свои потребности и ожидания от консультации с психологом.
    Полезно изучить квалификацию и практику специалиста.
    Рекомендации бывших обратившихся могут подсказать сделать решение более осознанным.
    Также нужно проверить методы, которыми оперирует специалист.
    https://dienstleistersuche.org/%D1%86%D0%B5%D0%BD%D1%82%D1%80-%D1%8D%D0%BC%D0%BF%D0%B0%D1%82%D0%B8%D1%8F-%D0%BF%D1%81%D0%B8%D1%85%D0%B8%D0%B0%D1%82%D1%80-%D0%BA%D0%BE%D1%82%D0%BE%D1%80%D0%BE%D0%BC%D1%83-%D0%BC%D0%BE/
    Первая встреча поможет почувствовать, насколько вам комфортно общения.
    Важно помнить цену и способ работы (например, онлайн).
    Осознанный выбор психолога поможет улучшить движение к целям.

  43. clinica implant par Bucuresti

Comments are closed.