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

    Tried these best thc tincture in the forefront bed a few times in and they in point of fact work. I’m usually tossing and turning, but with these I end up falling asleep in the way of quicker. No way-out hangover hint in the morning either. Kinda excessive, but fairly usefulness it when I just thirst for a textile darkness’s sleep.

  2. Patrickwrads's avatar Patrickwrads says:

    Покупка автозапчастей в сети является всё более популярной среди водителей.
    Онлайн-платформы предлагают широкий каталог деталей для самых разных моделей автомобилей.
    Цены в сайтах часто доступнее, чем в традиционных магазинах.
    Покупатели имеют возможность сопоставлять предложения разных поставщиков в несколько кликов.
    аккумулятор авто купить
    Кроме того, простая система логистики позволяет получить заказ без задержек.
    Оценки других пользователей помогают выбрать подходящие автозапчасти.
    Многие сервисы дают защиту на товары, что увеличивает доверие покупателей.
    Таким образом, заказ в сети автозапчастей экономит время и деньги.

  3. Heya! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing a few months of hard work due to no back up. Do you have any methods to stop hackers?

  4. I enjoy examining and I conceive this website got some really useful stuff on it! .

  5. DavidCix's avatar DavidCix says:

    Crash games are browser games with a interactive experience.
    They feature a rising multiplier that players can watch in real time.
    The goal is to act before the counter crashes.
    best cs2 crash sites
    Such games are popular for their straightforward play and excitement.
    They are often used to improve timing.
    A lot of platforms present crash games with varied designs and features.
    You can try these games now for a interesting experience.

  6. VigorMuse's avatar VigorMuse says:

    empowering ambitious women

  7. RandyDeext's avatar RandyDeext says:

    The platform allows you to swap clothes on images.
    It uses artificial intelligence to fit outfits naturally.
    You can test multiple styles right away.
    New Clothing Changer Tool
    The results look authentic and professional.
    It’s a convenient option for outfit planning.
    Upload your photo and choose the clothes you prefer.
    Begin trying it today.

  8. Charlesduh's avatar Charlesduh says:

    On this site you can discover a lot of useful information.
    It is created to guide you with different topics.
    You will get easy-to-read explanations and real examples.
    The content is constantly improved to stay current.
    https://sjch.us
    It’s a great resource for learning.
    Anyone can take advantage of the materials here.
    Begin reading the site today.

  9. RandyDeext's avatar RandyDeext says:

    This tool allows you to swap clothes on images.
    It uses artificial intelligence to adjust outfits realistically.
    You can try multiple styles right away.
    xnudes.ai|Unreal Clothes Changer AI Application
    The results look real and modern.
    It’s a convenient option for shopping.
    Upload your photo and pick the clothes you like.
    Begin using it now.

  10. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.info/en-ZA/register-person?ref=JHQQKNKN

  11. Kennethmup's avatar Kennethmup says:

    generic drugs mexican pharmacy rybelsus from mexican pharmacy mexico pharmacy

  12. RobertScort's avatar RobertScort says:

    Tried the 10mg thc effects from Cornbread Hemp — the benevolent with a access of THC. Took one before bed. The flavor’s polite, measure earthy but pleasant. Around an hour later, I felt noticeably more nonchalant — not lethargic, lawful serene adequate to drift eccentric without my tell off racing. Woke up with no morning grogginess, which was a minute surprise. They’re on the pricier side, but if you struggle to unwind at night, they could be advantage it.

  13. AI financial modeling crypto

  14. Kevingok's avatar Kevingok says:

    Современные системы учёта рабочих смен способствуют улучшению производительности .
    Удобный интерфейс минимизирует погрешности в планировании графиков.
    Руководителям удобнее анализировать рабочие графики дистанционно .
    https://bwingiris.net/tech/why-do-companies-need-hr-analytics-for/
    Работники пользуются гибким графиком при оформлении отпусков.
    Внедрение таких систем значительно ускоряет управленческие задачи с минимальными усилиями .
    Такой подход обеспечивает слаженность между отделами , сохраняя результативность команды .

  15. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://accounts.binance.info/en/register-person?ref=JHQQKNKN

  16. exchange USDT in Vienna

  17. Michaelincus's avatar Michaelincus says:

    Освоение английского с раннего возраста очень полезно.
    В этом возрасте способности ребёнка быстро адаптируется к новые знания.
    Первые шаги с иностранной речью поддерживает воображение.
    Кроме того, ребёнку удобнее осваивать другие языки в будущем.
    Навык английского создаёт многочисленные пути развития в учёбе и жизни.
    Таким образом, начало обучения английского становится основой будущего.
    https://nonghuachang-sao.go.th/forum/suggestion-box/570751-p-s-v-ui-gd-p-d-br-i-p-dh-djashchi-ur-i-ngliis-g

  18. For anyone who’s serious about finding a high-quality online casino, I can recommend WinCraft Casino without hesitation. It combines everything you’d want in a platform: tons of games, reliable payment options, professional live dealers, and strong security features. The loyalty rewards are especially impressive — the higher you go, the better the perks. Whether you prefer casual slot play or the intensity of live tables, this casino has something for everyone. See for yourself: https://win-craftcasino.com

  19. RobertScort's avatar RobertScort says:

    Tried the https://www.cornbreadhemp.com/collections/thc-gummies from Cornbread Hemp — the understanding with a access of THC. Took song anterior to bed. The flavor’s decent, lose earthy but pleasant. With reference to an hour later, I felt noticeably more nonchalant — not nodding, well-grounded appease enough to drift off without my tendency racing. Woke up with no morning grogginess, which was a good surprise. They’re on the pricier side, but if you struggle to unwind at tenebriousness, they could be advantage it.

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

  21. Robertlow's avatar Robertlow says:

    Compare Kamagra with branded alternatives Fast-acting ED solution with discreet packaging Men’s sexual health solutions online

  22. sell USDT in Manchester

Comments are closed.