Search code examples
c#visual-studio-macxamarin.mac

How can I pass data between views via segue in a Xamarin.mac Cocoa app?


I am developing a Xamarin.Mac Cocoa app in C# with visual studio for Mac.

I would like to pass an object from my first view controller to the next view controller. I have a segue called LaunchSecondView that starts the second view. And I need an object class Person from the first view in the second.


Solution

  • First, you need to set a public property in your second view controller :

    public Person MainPerson { get; set; }
    

    You’ll need to override the method called PrepareForSegue. Inside it, you identify the destination controller (your second view), and in case you have multiple segues, it is a good practice to use a switch case statement.


    public override void PrepareForSegue(NSStoryboardSegue segue, NSObject sender)
    {
        base.PrepareForSegue(segue, sender);
    
        switch (segue.Identifier)
        {
            case "LaunchSecondView":
                {
                    SecondViewClass target = segue.DestinationController as SecondViewClass;
                    target.Person = CurrentPerson;
                }
                break;
        }
    }