Shell Navigation and using a Dictionary to pass values.

Ronald Rex 1,666 Reputation points
2023-01-27T15:01:59.6933333+00:00

I am trying to learn how to pass complex data types to a page using a Dictionary. As you can see in the example code below that Name was hardcoded, but I was wondering what is the best practice if I wanted to dynamically set the Name property in the view model (using the value of a XAML control)? Thanks !!!


public class Monkey
{ 
    public string Name { get; set; }
}



Monkey monkey;
monkey = new Monkey { Name = "Mooch" };
  new Dictionary<string, object>
            {
                ["Monkey"] = monkey
            });
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,861 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,491 Reputation points Microsoft Vendor
    2023-01-30T08:15:55.4533333+00:00

    Hello,

    but I was wondering what is the best practice if I wanted to dynamically set the Name property in the view model (using the value of a XAML control)?

    If you get the Monkey object at the runtime in the viewmodel, then you want to update this object at the runtime without create a new Object. you can do this by achieving INotifyPropertyChanged interface for your Monkey.cs.

    public class Monkey: INotifyPropertyChanged
    {
        private string name;
        public string Name
        {
            set
            {
                if (name != value)
                {
                    name = value;
                    OnPropertyChanged("Name");
                }
            }
            get
            {
                return name;
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    } 
    

    Then you can set the Name directly with monkey.Name="Mooch" and send it

    Here is document about Part 5. From Data Bindings to MVVM - Xamarin | Microsoft Learn

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.