xamarin tutorial

Upload: alex-hitch

Post on 17-Oct-2015




1 download


Xamarin Tutorial


  • ll




    Hello, Mac


    Using Xamarin.Mac, you can create native Mac applications by using the same UI controls that youwould if you were writing the application in Objective-C and Xcode, except you have the flexibilityand elegance of a modern language (C#), the power of the .NET Base Class Library (BCL), and afirst-class IDE (Xamarin Studio) at your fingertips.

    Additionally, Xamarin.Mac integrates directly with Xcode so that you can use the integrated Interface Builder (IB) to create your applications user interface.

    In this tutorial, were going to walk through creating a simple application from start to finish. Wellcover the following items:

    Xamarin Studio (MD) Introduction to the Xamarin IDE (Xamarin Studio) and how to createXamarin.Mac applications with it.Anatomy of a Xamarin.Mac Application What a Xamarin.Mac application consists of.Xcodes Interface Builder How to use Xcodes Interface Builder to define your applicationsuser interface (UI).Outlets and Actions How to use Outlets and Actions to wire up controls in the UI.Deployment/Testing How to run your application and test it out.

    The following is a screenshot of the application that were going to build, running in Mountain Lion(Mac OS X 10.8):

  • Lets jump in.

    Introduction to Xamarin Studio

    Nearly all Xamarin.Mac tutorials are based on using Xamarin Studio as the Integrated DevelopmentEnvironment (IDE) of choice. Xamarin Studio is a free, open-source IDE, and is very similar to otherIDEs such as Eclipse or Visual Studio.

    Lets begin by launching Xamarin Studio. You can find it in either your Applications directory, or via aSpotlight search for Xamarin Studio.

    Xamarin Studio should open up and look something like the following:

  • Lets jump right in and begin our first Xamarin.Mac application.

    Creating a New Xamarin.Mac Project

    From the Xamarin Studio Home screen, choose Start a New Solution:

    In the left-hand pane, choose C# > Xamarin.Mac, and then, in the center pane, select Xamarin.MacProject template. This will create a new single window Mac application.

  • ll

    If you are using the trial, select "Mac (open source)" which uses the more limited set of APIs.

    Lets name it Hello_Mac. Choose a location where youd like the solution to reside, and click OK.

    Xamarin Studio will create a new Xamarin.Mac application and solution that looks something like thefollowing:

    This should be pretty familiar territory if youve used an IDE before. There is a Solution Explorer pad that shows all the files in the solution, and a code editor pad that allows you to view and editthe selected file.

    Xamarin Studio uses Solutions and Projects, the exact same way that Visual Studio does. A solutionis a container that can hold one or more projects; projects can include applications, supportinglibraries, test applications, etc. In this case, Xamarin Studio has created both a solution and anapplication project for you. If you wanted to, you could create code library projects that theapplication project uses, just as you would if you were building a standard .NET application.

    The Project

    If youre familiar with iOS programming, youll notice a lot of similarities here. In fact, iOS uses theCocoaTouch framework, which is a slimmed-town version of Cocoa, used by Mac. In fact, a lot ofconcepts will cross over here.

    Lets take a look at the files in the project:

    Main.cs This contains the main entry point of the application. When the application is launched,this contains the very first class and method that is run.AppDelegate.cs This file contains the main application class that is responsible for listening toevents from the operating system.

  • ll





    Info.plist This file contains application properties such as the application name, icons, etc.MainMenu.xib This is the UI for the application menu. .Xib files (also referred to as Nibs forlegacy reasons), are XML files that contain the definition of views (UI elements).MainWindow.cs This is the class that represents the main window and controls the lifecycle of it.MainWindow.designer.cs This file contains plumbing code that helps you integrate with the mainscreens user interface.MainWindow.xib The UI for the main window.MainWindowController.cs This is the controller for the main window. Well cover controllers in thenext guide, but for now, a controller can be thought of the main engine of any particular view.

    Lets take a quick look through some of these files. Well explore them in more detail later, and inother tutorials, but its a good idea to understand their basics now.


    The Main.cs file is very simple. It contains a static Main method which creates a new Xamarin.Macapplication instance and passes the name of the class that will handle OS events, which in our caseis the AppDelegate class:

    using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; usingMonoMac.ObjCRuntime; namespace Hello_Mac { class MainClass { static void Main (string[] args) {NSApplication.Init (); NSApplication.Main (args); } } }


    The AppDelegate.cs file contains our AppDelegate class, which is responsible for creating our windowand listening to OS events:

    using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; usingMonoMac.ObjCRuntime; namespace Hello_Mac { public partial class AppDelegate : NSApplicationDelegate{ MainWindowController mainWindowController; public AppDelegate () { } public override voidFinishedLaunching (NSObject notification) { mainWindowController = new MainWindowController ();mainWindowController.Window .MakeKeyAndOrderFront (this); } } } This code is probably unfamiliar unless youve built an iOS application before, but its fairly simple.Lets examine the important lines.

    First, lets take a look at the two class-level variable declarations:

    MainWindowController mainWindowController; The MainWindowController declaration represents what controls the actual application window.Generally, for every window you create (and for many other things within windows), there is acontroller, which is responsible for the windows life cycle, such as showing it, adding new views(controls) to it, etc.

    Cocoa (and by derivation, CocoaTouch) uses whats known as the Model View Controller (MVC)pattern. Well examine this in more depth in the next tutorial, when we create an application withmultiple windows.

    Next, we have the FinishedLaunching method. This method runs after the application has beeninstantiated, and its responsible for actually creating the application window and beginning theprocess of displaying the view in it.

    The first line instantiates a new instance of our main window controller:

  • mainWindowController = new MainWindowController (); Next, the code tells the main window (the Window property on the controller) that it should be in focusand accept user input (Key), and appear in the front of any other windows:

    mainWindowController.Window.MakeKeyAndOrderFront (this);


    As weve already seen, the MainWindowController class is our main windows controller. That meansits responsible for the life cycle of the main window. Were going to examine this in detail later, sowe can skip any more detail about it for now:

    using System; using System.Collections.Generic; using System.Linq; using MonoMac.Foundation; usingMonoMac.AppKit; namespace Hello_Mac { public partial class MainWindowController :MonoMac.AppKit.NSWindowController { #region Constructors // Called when created from unmanaged codepublic MainWindowController (IntPtr handle) : base (handle) { Initialize (); } // Called whencreated directly from a XIB file [Export ("initWithCoder:")] public MainWindowController (NSCodercoder) : base (coder) { Initialize (); } // Call to load from the XIB/NIB file publicMainWindowController () : base ("MainWindow") { Initialize (); } // Shared initialization code voidInitialize () { } #endregion //strongly typed window accessor public new MainWindow Window { get {return (MainWindow)base.Window; } } } } The Window property is a convenience property that casts the base.Window property to a strongly-typedversion of the actual Window class, so that any properties on there (as well see later) are availablewithout having to cast it every time you want to access them.


    The designer file for the Main Window class is empty right now, but it will be automatically populatedby Xamarin Studio as we create our UI:

    namespace Hello_Mac { // Should subclass MonoMac.AppKit.NSWindow[MonoMac.Foundation.Register("MainWindow")] public partial class MainWindow { } // Should subclassMonoMac.AppKit.NSWindowController [MonoMac.Foundation.Register("MainWindowController")] publicpartial class MainWindowController { } } We arent usually concerned with designer files, as theyre just automatically managed by XamarinStudio and just provide the requisite pluming code that allows access to controls that we add to anywindow or view in our application.

    Now that we have created our Xamarin.Mac application and we have a basic understanding of itscomponents, lets jump over to Xcode and create our UI.

    Introduction to Xcode and Interface Builder

    As part of Xcode, Apple has created a tool called Interface Builder (IB), which allows you to createyour UI visually in a designer. Xamarin.Mac integrates fluently with IB, allowing you to create your UIwith the same tools that Objective-C users do.

    Its important to note that you dont have to use IB to create your UI; you can also build itprogrammatically.

    Lets go ahead and walk through how to use IB to define our UI. Double-click on the MainWindow.xib file in Xamarin Studio. This should launch Xcode and look something like the following:

  • If Xcode doesnt open up, you can right-click on the file and choose Open With : Xcode.

    Lets do a quick overview of Xcode to orient ourselves.

    Components of Xcode

    When you open a Xib in Xcode from MD, Xcode opens with the Navigator Area on the left and the Editor Area in the middle, and the Utilities Area on the right:

  • When a .xib file is open, the Editor Area surface is whats known as Interface Builder (IB).

    In previous versions of Xcode, IB was a separate application. If you dont see the Utilities Area, youcan make it display by clicking the far-right button in the View section of the toolbar:

    The Utility Area is mostly empty because nothing is selected; however, if you select a control (or themain view), it will populate. The Utility Area is further broken down into two sub-areas, InspectorTabs and Library Tabs:

  • In the Library Tabs Area, you can find controls and objects to place into the designer. The InspectorTabs are kind of like property pages, where you can examine and edit control instances in the

  • ll








    There are 8 different Inspector Tabs, as shown in the following illustration:

    From left-to-right, these tabs are:

    File Inspector New in Interface Builder 4, the File Inspector shows file information, such asthe file name and location of the Xib file that is being edited.Quick Help Also new in Interface Builder 4, the Quick Help tab is part of Xcode 4s redesignedhelp system. It provides contextual help based on what is selected in Xcode.Identity Inspector The Identity Inspector provides information about the selected control/view.Attributes Inspector The Attributes Inspector allows you to customize various attributes ofthe selected control/view.Size Inspector The Size Inspector allows you to control the size and resizing behavior of theselected control/view.Connections Inspector The Connections Inspector shows the Outlet and Action connectionsof the selected controls. Well examine Outlets and Actions in just a moment.Bindings Inspector The Bindings Inspector allows you to configure controls so that theirvalues are automatically bound to data models.View Effects Inspector The View Effects Inspector allows you to specify effects on thecontrols, such as animations.

    Creating the Interface

    Now that were familiar with the Xcode IDE and IB, lets actually use IB to create the UI of our mainview. Were going to use IB to create the following:


    To create this UI:

    Drag a Push Button and a Label to the designer from the third tab of the Library.To resize the controls, select them and then pull on their resize handles.Double-click on the button to set its text.Make the label nearly as wide as the view. This will let us update the label with text when thebuttons are clicked.

    As youre resizing and moving controls around, youll notice that IB gives you helpful snap hints thatare based on Apples Human Interface Guidelines (HIG). These guidelines will help you create highquality applications that will have a familiar look and feel for Mac users.

    While we have IB open, lets look at one other useful area, the Document Inspector. The DocumentInspector is just to the left of the Editor Area and can be expanded by clicking the > arrow button atthe bottom of the area:

    The Document Inspector shows you all of the items in a tree and allows you to select them:

  • ll

    If you have a complicated UI, this can be a great alternative to using the designer window.

    OK, now that we have created our UI, we need to wire up our Outlets to code.

    Outlets and Actions

    Xamarin Studio created a file called MainWindowController.h as part of the Xcode project itgenerated to use the designer. This .h file is a stub file that Xamarin Studio created to mirror theDesigner.cs file. This is where well use Xcode to define our Outlets. Xamarin Studio will thensynchronize the changes to this file with the designer file.

    Outlets + Actions Defined

    So what are Outlets and Actions? In traditional .NET UI programming, a control in the UI isautomatically exposed as a property when its added. Things work differently in Mac (and in iOSprogramming, for that matter). Simply adding a control to a view doesnt make it accessible to code.In order to access our controls from code, Apple gives us two options:

    Outlets Outlets are analogous to properties. If you wire up a control to an Outlet, its exposedto your code via a property, so you can do things like attach event handlers, call methods on it,etc.Actions Actions are analogous to the command pattern in WPF. For example, when an Actionis performed on a control, say a button click, the control will automatically call a method in yourcode. Actions are powerful and convenient because you can wire up many controls to the sameAction.

    In Xcode 4, Outlets and Actions are added directly in code via Control-dragging. More specifically,this means that in order to create an Outlet or Action, you choose which control element youd like to

  • add an Outlet or Action, hold down the Control button on the keyboard, and drag that control directlyinto your code.

    For Xamarin.Mac developers, this means that you drag into the Objective-C stub files thatcorrespond to the C# file where you want to create the Outlet or Action.

    In order to facilitate this, Xcode 4 introduced a split-view in the Editor Area called the Assistant Editor that allows two files to be visible at once (the .xib file in the Interface Builder designer, and the codefile in the code editor).

    In order to view the Assistant Editor split screen, click the middle button of the Editor choice buttonsin the toolbar:

    Xcode will then show the designer and .h file at once:

    Now we can start wiring up our Outlets, we wont use Actions in this application, but the process isnearly exactly the same.

    Adding an Outlet

    Before we start to wire up our Outlets, we first need to make sure that theyre going to get wired upin the right file. In the Assistant Editor, choose the file drop down just above the editor, and makesure that the MainWindowController.h file is chosen:

  • 1.


    In this case, we could wire up the Outlets to the window file, but in practice, Outlets are should nearlyalways be put in controllers (where theyll be used). So well get in the habit now.

    Once weve made sure that the right file is chosen, lets perform the following procedure to createour Outlets:

    Determine for which control you want an Outlet. To start with, were going to create an outlet forthe Click Me button.Hold down the Control key on the keyboard, and then drag from the control to an empty spacein your code file after the @interface definition:

    You can drag from the Document Inspector as well, which can be helpful if you have a complicatedUI with nested controls.

    A popover will then show, giving you the option to choose either Outlet or Action. Choose Outlet andname it ClickMeButton:

  • Click Connect after youve filled out the form, and Xcode will insert the appropriate code in the .h file:

    Save the file, and then go back to Xamarin Studio. In the MainWindow.designer.cs file we should nowsee our new Outlet exposed as a property on the MainWindowController class:

  • Note that this is a partial class, so that Xamarin Studio doesnt have to edit our MainWindowController.cs file.

    As you can see, Xamarin Studio listens for changes to the .h file, and then automaticallysynchronizes those changes in the respective designer.cs file to expose them to your application.

    We need to create one more Outlet for our label, so lets switch back over to Xcode. Create thelabels Outlet the same way we did the buttons Outlet and name it OutputLabel. The .h file shouldhave the following Outlets now defined:

    @property (assign) IBOutlet NSButton *ClickMeButton; @property (assign) IBOutlet NSTextField*OutputLabel; Now that we have our Outlets wired up, lets save the files and switch back to Xamarin Studio toactually do something interesting with them.


    It probably took a long time to create the UI and Outlets for our first application, and it may seem likea lot of work, but weve introduced a lot of new concepts and weve spent a lot of time covering newground. Once youve practiced awhile working with IB, this interface and all its Outlets can becreated in just a minute or two.

    Writing the Code

    In our application, every time the first button is clicked, were going to update our label to show howmany times the button has been clicked. In order to accomplish this, we need to do two things. First,we need to create a class-level variable in our MainWindowController class to track the number ofclicks that have happened:

    public partial class MainWindowController : MonoMac.AppKit.NSWindowController { protected int

  • ll


    numberOfTimesClicked = 0; } Next, in the same class (MainWindowController), we need to override the AwakeFromNib method andadd some code to update our label with the number of times the button was clicked:

    public override void AwakeFromNib () { base.AwakeFromNib (); ClickMeButton.Activated += (objectsender, EventArgs e) => { numberOfTimesClicked++; OutputLabel.StringValue = "Clicked " +numberOfTimesClicked + " times."; }; } We need to use AwakeFromNib, instead of another method such as Initialize, because AwakeFromNib iscalled after the OS has loaded the UI from the .xib file. If we tried to access the button control beforethe .xib file has been fully hydrated, wed get a NullReferenceException error because the buttoncontrol would not be created yet.

    Also notice that we used the Activated event on the button. Its kind of a strange name but its theevent that gets raised when the button is clicked.

    Thats it! Weve created our first Xamarin.Mac application, so now its time to run it and test it!

    Testing the Application

    Its time to build and run our application; to see it in action and make sure it runs as expected. Wecan build and run all in one step, or we can build it without running it.

    Lets build it first, just to learn how to build without deploying. Whenever we build an application, wecan choose what kind of build we want:

    Debug A debug build is compiled into an .app (application) file with a bunch of extra metadatathat allows us to debug whats happening while the application is running.Release A release build also creates an .app file, but it doesnt include debug information, soits smaller and executes faster.AppStore An AppStore build creates a signed application package that is ready to submit tothe App Store.

    In our case, we just want a debug build, so lets make sure that Debug|x86 is selected in the builddrop down:

    Then, either press +B, or from the Build menu, choose Build All. If there are no errors, youll see a Build Succeeded message in the status bar of Xamarin Studio. If there are errors, review yourprocedure and make sure that youve followed the steps correctly. Start by confirming that your code(both in Xcode and in Xamarin Studio) matches the code in the tutorial.

    Running the Application

    To run the application, we have three options:

  • ll


    Press +EnterFrom the Run menu, choose DebugClick the Gear icon with the green circle from the build toolbar.

    The application will build (if it hasnt been built already) and if we click the button a few times, weshould see something like following:

    Congrats, youve now built and run your very first Xamarin.Mac application!


    Congratulations! We covered a lot of ground here, but if you followed this tutorial from start to finish,you should now have a solid understanding of the components of a Xamarin.Mac application as wellas the tools used to create them.

    In the next guide, were going to take a look at the Model, View, Controller (MVC) pattern in Mac andhow its used to create more complex applications.

    Hello, MacOverviewIntroduction to Xamarin StudioCreating a New Xamarin.Mac Project

    The ProjectMain.csAppDelegate.csMainWindowController.csMainWindow.Designer.cs

    Introduction to Xcode and Interface BuilderComponents of XcodeCreating the InterfaceOutlets and ActionsOutlets + Actions DefinedAdding an Outlet

    Writing the CodeTesting the ApplicationRunning the Application