.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. Stephenviaps's avatar Stephenviaps says:

    Finding content that strikes the perfect balance between being thorough and remaining highly accessible is a rare treat, so I wanted to drop a quick thank you for sharing this excellent summary with everyone today.

    nuevo casino bono sin deposito

  2. DichaelAlono's avatar DichaelAlono says:

    I genuinely enjoyed reading this carefully written piece. The neutral approach you took helps clarify the main points beautifully, making it very easy for the audience to digest.

    https://dollyolive.co.uk/

  3. hiteBize's avatar hiteBize says:

    ?? ?????? ??????? ???? ??????????? ?????????? ???????? ?????????? ?????? ??????????.
    ????? ??????? ?????????????? ????????? ?? ?????????? ???????.
    ?? ??? ????? ????????????? ? ??????????? ???????? ? ????????.
    ? ??????????? ??????? ?????????? ??? ?????????? ? ???????????? ? ??????? ????????.
    ????????? ??????????? ??????????? ??????, ????? ?? ?????????? ? ????.
    https://md2014.ru/item/213-tramp-predskazyvaet-vozmozhnuyu-podpis-iranskogo-soglasheniya-v-evrope-uzhe-v-eti-vykhodnye/

  4. Слушайте кто подъемники ищет Цены космос а качество мыло То тали бракованные Короче, нашел нормальных производителей — оборудование для подъема грузов до 50 тонн Цены ниже чем у перекупов на 20% В общем, сохраняйте себе — цепная ручная таль https://tal-elektricheskaya.ru Не ведитесь на дешевые предложения Перешлите тому кто ищет оборудование

  5. Грунт широко используется в аграрном хозяйстве для культивации культур.
    В закрытых помещениях грунт служит основой для овощных растений.
    На плантациях земля задействуется для посева зерновых и промышленных культур.
    растительный грунт с доставкой цена
    Почвенные составы необходимы для создания газонов и ландшафтного оформления.
    В дендрариях грунт играет важную роль при получении посадочного материала.
    Кроме того почва применяется для оздоровления деградированных участков.

  6. Проктологическая проблема нуждается в своевременного лечения, так как запущенный стадия приводит к осложнениям.
    При отсутствии правильной терапии признаки нарастают: дискомфорт, жжение и кровотечение становятся постоянными.
    Заболевание может спровоцировать закупорку вен, анемию и даже инфекцию близлежащих тканей.
    где сделать колоноскопию
    Лечение на ранних ступенях даёт возможность использовать малоинвазивные методы, избегая операционного вмешательства.
    Нынешние средства и процедуры обеспечивают скоростной результат и незначительный болевых ощущений для пациента.
    Своевременное посещение к проктологу помогает нормализовать качество жизни и предотвратить тяжёлых осложнений.

  7. Dennisves's avatar Dennisves says:

    ссылка на сайт vodkabet

  8. Dennisves's avatar Dennisves says:

    проверить сайт водкабет

  9. Tirz.pro's avatar Tirz.pro says:

    Лекарство Оземпик считается современным средством для лечения диабета 2 типа.
    Этот медикамент используется инъекционно один раз неделю посредством эргономичной ручки-дозатора.
    Центральное действие Оземпика — стимулировать рецепторы, вызывая снижение глюкозы в крови.
    Tirz.pro
    Кроме контроля гликемии, это средство помогает постепенному снижению веса.
    Курс Оземпика должен назначаться только эндокринологом с учётом всех противопоказаний.
    При терапии могут встречаться нежелательные эффекты, например тошнота или нарушение стула, которые часто исчезают со временем.

  10. Trust me, I’ve learned everything the hard way so you don’t have to. You see this gorgeous deal online — clean spec, fair price, looks like a dream. Plus they put a surprise $4000 hold on your card and say it’ll take two weeks to release right before giving you the keys. Fool me eleven times? That’s just called living in Miami, lesson learned. When you’re searching for a legit and reliable premium ride to cruise around, do some real digging first and read actual customer reviews. Miami without proper wheels is basically a disaster, whether you are doing Key Biscayne sunset, Design District shopping, or a spontaneous drive down to the Everglades.

    Most of these local agencies are just shiny garbage with fake Google reviews bought in bulk hiding overpriced junk, but I eventually found a service with no games, no switch, and no hidden BS in paragraph 12 of the contract. If you are looking for the only honest source for premium rides across South Florida, check the current details here: opf fl luxury car rentals opf fl luxury car rentals. Yeah, parking in South Beach will cost you a nice bottle of champagne — but that’s the Miami tax. Just drive safe out there and definitely skip that “tire and wheel” upsell — pure profit for them, zero value for you. let me know if you guys have any other clean spots.

  11. I personally find that the testing new tokens process is simple and the reliable uptime makes it even better. Definitely recommend to anyone in crypto.

Leave a Reply

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