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
            });
Developer technologies | .NET | .NET MAUI
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.