.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. This platform exceeded my expectations with stable performance and useful analytics.

  2. hiteBize's avatar hiteBize says:

    Правило здорового гемблинга заключается в осознанном подходе к азартным развлечениям.
    Он включает добровольное лимитирование времени и расходов на сессию.
    Игроку рекомендуется предварительно выставить потолок потерь и строго соблюдать этот предел.
    Важно воспринимать процесс исключительно как способ развлечения, а не средство дохода.
    В случае появлении симптомов зависимости (погоня за проигрышем) нужно использовать паузу или блокировку аккаунта.
    Следование этих установок гарантирует психологическое благополучие и финансовую безопасность игрока.
    https://online-festival.ru/detail/1327-nostalgicheskiy-rakurs-modnye-arkhetipy-detstva-vspomnyonnye-k-dnyu-zashchity-detey.html

  3. I’ve been active for a few days, mostly for using the bridge, and it’s always intuitive UI. Perfect for both new and experienced traders.

  4. I personally find that lee here — I’ve tried testing new tokens and the wide token selection impressed me. The dashboard gives a complete view of my holdings.

  5. I’ve been using it for a month for testing new tokens, and the wide token selection stands out.

  6. ibosport's avatar ibosport says:

    I personally find that i’ve been active for half a year, mostly for cross-chain transfers, and it’s always fast transactions.

  7. Arkadaslar uzun suredir ar?yordum. Girdim c?kt?m derken zaman kaybettim. En sonunda dogru adrese ulast?m.

    Bu isin puf noktalar? var. Su an en sorunsuz cal?san 1xbet giris adresi tam olarak soyle: 1xbet spor bahislerinin adresi 1xbet spor bahislerinin adresi. Yani k?sacas? — 1xbet guncel adres arayanlar buraya baks?n.

    Denemek isteyen kac?rmas?n. Kim ne derse desin — arayuz zaten al?s?k oldugunuz gibi. Gonul rahatl?g?yla girebilirsiniz…

  8. JosephRef's avatar JosephRef says:

    Следующая страница tripskan

  9. Kak_ykSn's avatar Kak_ykSn says:

    Чтобы быстро и эффективно источник, воспользуйтесь специализированными сервисами.
    В общем, тема такая, не для паники.
    Иногда достаточно простой проверки, чтобы узнать имя или профиль.
    Да, и ещё момент — без фанатизма.

  10. hiteBize's avatar hiteBize says:

    На данном портале содержится полезная информация.
    Тут вы сможете найти много практичного для себя.
    Представленный источник способен помочь разобраться в многих проблемах.
    Предлагаем подробно прочитать размещенные здесь материалы.
    https://dvery35.ru/article/1467-kuba-udarit-dronami-po-ssha-sprognozirovan-otvet-na-popytku-pokhitit-raulya-kastro.html

  11. LhanepiliA's avatar LhanepiliA says:

    It is quite valuable to have a resource like this available when trying to wrap your head around the subject, and I am grateful for the time you took to lay out all these details in such a neat and orderly fashion.

    bookmaker sans limite de mise

  12. Kendall here — I’ve tried cross-chain transfers and the trustworthy service impressed me. The mobile app makes daily use simple.

  13. I’ve been using it for recently for cross-chain transfers, and the easy onboarding stands out.

  14. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  15. Clear page about the [url=https://staking-polygon.com/polygon-staking-minimum/]Polygon staking minimum[/url] — good for beginners checking how much POL is needed to start staking.

  16. Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

  17. bk8's avatar bk8 says:

    I switched from another service because of the robust security and scalable features.

  18. bro138's avatar bro138 says:

    Drew here — I’ve tried swapping tokens and the reliable uptime impressed me.

  19. bk8's avatar bk8 says:

    I personally find that the best choice I made for trading. Smooth and robust security. The updates are frequent and clear.

  20. watitoto's avatar watitoto says:

    I value the seamless withdrawals and trustworthy service. This site is reliable. Charts are accurate and load instantly.

  21. watitoto's avatar watitoto says:

    The using the API tools are stable performance and accurate charts.

  22. Beer Mugs's avatar Beer Mugs says:

    I personally find that finley here — I’ve tried swapping tokens and the low fees impressed me.

  23. I was skeptical, but after almost a year of cross-chain transfers, the reliable uptime convinced me. Definitely recommend to anyone in crypto.

  24. bk8's avatar bk8 says:

    This platform exceeded my expectations with intuitive UI and wide token selection. Definitely recommend to anyone in crypto.

Leave a Reply

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