February 27, 2015

Give Us the Gist of It Contest Winners!


Two weeks ago, we asked the community to share the code snippets that help them write amazing apps even faster. Five winners were chosen at random, and here is the gist of it:

Jason Fox:
Snippet Name: Xamarin.iOS Image Blur
Platform: Xamarin.iOS
Function: Image blur extension method for Xamarin.iOS

public static UIImage Blur(this UIImage image, float blurRadius = 25f)
  if (image != null)
    // Create a new blurred image.
    var imageToBlur = new CIImage (image);
    var blur = new CIGaussianBlur ();
    blur.Image = imageToBlur;
    blur.Radius = blurRadius;
    var blurImage = blur.OutputImage;
    var context = CIContext.FromOptions (new CIContextOptions { UseSoftwareRenderer = false });
    var cgImage = context.CreateCGImage (blurImage, new RectangleF (new PointF (0, 0), image.Size));
    var newImage = UIImage.FromImage (cgImage);
    // Clean up
    imageToBlur.Dispose ();
    context.Dispose ();
    blur.Dispose ();
    blurImage.Dispose ();
    cgImage.Dispose ();
    return newImage;
  return null;

Runar Ovesen Hjerpbakk:
Snippet Name: Async and await together with UIAlertController
Platform: Xamarin.iOS
Function: This snippet shows how to use a TaskCompletionSource to enable async and await together with UIAlertController.

public static class CustomerFeelingSheet {
 public static Task<CustomerFeeling> ShowRatingDialogAsync(UIViewController parent) {
   var taskCompletionSource = new TaskCompletionSource<CustomerFeeling>();
   var alert = UIAlertController.Create("howDoYouFeel".T(), null, UIAlertControllerStyle.ActionSheet);
   alert.AddAction(UIAlertAction.Create("likeIt".T(), UIAlertActionStyle.Default,
       a => taskCompletionSource.SetResult(CustomerFeeling.LikeIt)));
   alert.AddAction(UIAlertAction.Create("couldBeBetter".T(), UIAlertActionStyle.Default,
       a => taskCompletionSource.SetResult(CustomerFeeling.CouldBeBetter)));
   alert.AddAction(UIAlertAction.Create("cancel".T(), UIAlertActionStyle.Cancel,
       a => taskCompletionSource.SetResult(CustomerFeeling.DontCare)));
   parent.PresentViewController(alert, true, null);
   return taskCompletionSource.Task;

Matthieu Guyonnet-Duluc:
Snippet Name: Android Behavior – WPF Style
Platform: Xamarin.Android
Function: Reproduce the beloved WPF behaviors in Android

        local:View="@+id/resultsList" />
    public class ListViewHideKeyboardOnScroll : Behavior<AbsListView>
        public ListViewHideKeyboardOnScroll(Context context, IAttributeSet attrs)
            : base(context, attrs)
        #region implemented abstract members of Behavior
        public override void OnAttached()
            View.ScrollStateChanged += HideKeyboard;
        public override void OnDetached()
            View.ScrollStateChanged -= HideKeyboard;
        void HideKeyboard(object sender, AbsListView.ScrollStateChangedEventArgs e)
            if (e.ScrollState == ScrollState.TouchScroll)
                var inputManager = (InputMethodManager)this.Context.GetSystemService(Context.InputMethodService);
                inputManager.HideSoftInputFromWindow(View.WindowToken, HideSoftInputFlags.None);

Ken Pespisa:
Snippet Name: SQLite Extension methods for Save & Delete
Platform: Xamarin.iOS
Function: Save the specified entity by calling insert or update, if the entity already exists.

public static class SQLiteExtensions
   /// <summary>
   /// Save the specified entity by calling insert or update, if the entity already exists.
   /// </summary>
   /// <param name="pk">The primary key of the entity</param>
   /// <param name="obj">The instance of the entity</param>
   /// <typeparam name="T">The entity type.</typeparam>
   public static int Save<T>(this SQLiteConnection db, object pk, object obj) where T : new()
       if (pk == null || db.Find<T>(pk) == null)
           return db.Insert(obj);
       return db.Update(obj);
   /// <summary>
   /// Delete entities based on a predicate function
   /// </summary>
   /// <param name="predicate">The predicate specifying which entities to delete</param>
   /// <typeparam name="T">The entity type.</typeparam>
   public static void Delete<T>(this SQLiteConnection db, Expression<Func<T, bool>> predicate) where T : new()
       var records = db.Table<T>().Where(predicate).ToList();
       foreach (var record in records)

Ryan Davis:
Snippet Name: InlineTableViewSource
Platform: Xamarin.iOS
Function: A subclass of UITableViewSource that allows you to define UITableViewDataSource and UITableViewDelegate methods inline, rather than subclassing.

var cellId = new NSString("cell");
var tableView = new UITableView(View.Frame, UITableViewStyle.Grouped) {
    Source = new InlineTableViewSource {
            _NumberOfSections = (tv) => 2,
            _RowsInSection = (tv, section) => 5,
            _TitleForHeader = (tv, section) => String.Format("Section {0}", section),
            _GetCell = (tv, indexPath) => {
                var cell = tv.DequeueReusableCell(cellId) ?? new UITableViewCell(UITableViewCellStyle.Default, cellId);
                cell.TextLabel.Text = "hi";
                return cell;

Find even more speedy code snippets for your apps in the Get The Gist forum thread, and a big thanks to all who participated in the Give Us the Gist of It Contest!

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 26, 2015

Join Xamarin for GSMA Mobile World Congress 2015


Mobile World Congress LogoXamarin will take the stage alongside Airwatch, Box and Salesforce in Barcelona at Mobile World Congress next week.
Xamarin’s Director of Enterprise Mobility, Steve Hall, will join the Steve Hall“Airwatch Presents a New Standard for Enterprise App Development” panel discussion on March 2nd. Employees expect – and need – fast, on-the-go access to company data, and we’ll share how enterprises can successfully build and distribute secure mobile apps.

AirWatch Presents a New Standard for Enterprise App Development featuring Box, Salesforce & Xamarin

Tuesday, March 3, 1:30 – 2:25 pm CET
AirWatch Connect Stand
Hall 3, Stand 3D10
All MWC Attendees are welcome to attend.

See you in Barcelona!

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 25, 2015

Triggers in Xamarin.Forms


Triggers were introduced in Xamarin.Forms 1.3 along with Behaviors, which we covered previously. Triggers allow you to declaratively express actions in XAML that are executed when a specified condition is met. Xamarin.Forms support four types of triggers:

  • Property Trigger – executed when a property on a control is set to a particular value.
  • Data Trigger – same as the property trigger but uses data binding.
  • Event Trigger – occurs when an event occurs on the control.
  • Multi Trigger – allows multiple trigger conditions to be set before an action occurs.

Let’s take a look at each one in detail.

Property Trigger

Property Triggers (represented by the Trigger element) are added to a control’s Triggers collection. The Setter collection inside is executed when a specified property equals the specified value.


Wouldn’t it be nice to provide some visual indicator that an input control has focus? To achieve this, we can set the BackgroundColor property when the property IsFocused of the Entry element is true.

<Entry Placeholder="enter name">
        <Trigger TargetType="Entry"
             Property="IsFocused" Value="True">
                Value="Yellow" />

Alternatively, we can set them in styles so that they can be attached to every Entry element in the screen.

     <Style TargetType="Entry">
       <Setter Property="AnchorX" Value="0" />
         <Trigger  TargetType="Entry"
           <Setter Property="BackgroundColor"
                   Value="Yellow" />

Data Trigger

DataTriggers are very similar to PropertyTriggers, except that instead of specifying the Property, we specify the Binding for the trigger. This Binding generally refers to another VisualElement’s property on the page or it could reference a property in a ViewModel.

The code below shows how to disable the button when the entry’s Text.Length property is 0.

<StackLayout Spacing="20">
<Entry x:Name="emailAddress" Text="" Placeholder="email address"/>
<Button Text="Send">
    <DataTrigger TargetType="Button"
         Binding="{Binding Source={x:Reference emailAddress},
      <Setter Property="IsEnabled" Value="False" />

Event Trigger

Event Triggers execute user-defined code when a specified event occurs.

In the above Property Trigger example, we saw how to change the background color of an Entry element based on the IsFocused property entirely in XAML. Alternatively, we can use an Event Trigger to execute an action written in C# based on the TextChanged event of an entry to perform some basic validation.

Define the TriggerAction in code

Every action that we define has to inherit from TriggerAction<T> where T is the element to which a trigger is attached. When a trigger is fired, the Invoke method will be called. In the code below, we change the Entry’s BackgroundColor to indicate whether the input is valid or not.

public class NumericValidationTriggerAction : TriggerAction<Entry>
   protected override void Invoke (Entry entry)
      double result;
      bool isValid = Double.TryParse (entry.Text, out result);
      entry.BackgroundColor =
            isValid ? Color.Default : Color.Red;

TriggerAction in XAML

To use the C# code, just declare a namespace for the assembly (xmlns:local in this sample) and add the NumericValidationTriggerAction element to the event trigger:

<Style TargetType="Entry">
    <EventTrigger Event="TextChanged">
        <local:NumericValidationTriggerAction />

Multi Trigger

A MultiTrigger looks similar to a Trigger or DataTrigger except there can be more than one condition. All the conditions must be true before the Setters are triggered.

In the code below, we enable the button when either the email or the phone entries are filled in by the user. Each condition is true when the length of the text input is zero (ie. nothing has been entered). When both conditions are true (ie. both are empty) then the trigger’s Setters are called, which in this case disables the button. When either have text entered, the overall condition becomes false and the button is enabled.

<Style TargetType="Button">
  <MultiTrigger TargetType="Button">
          Binding="{Binding Source={x:Reference email},
          Value="0" />
          Binding="{Binding Source={x:Reference phone},
          Value="0" />
    <Setter Property="IsEnabled" Value="False" />

To see how to build a “require all” trigger (like you’d use in a login page, for example) check out our Triggers sample on GitHub that uses an IValueConverter along with a MultiTrigger.

For even more information on Xamarin.Forms, be sure to check out the detailed documentation.

Discuss this post in the Xamarin forums

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 24, 2015

Live APAC Webinar: Go Mobile with Xamarin


Photo of Mayur Tendulkar

Join Xamarin Evangelist Mayur Tendulkar for this live webinar timed just for our APAC customers, where you’ll learn how to leverage your existing Microsoft .NET and C# skills to build iOS, Android, and Windows Phone apps using Visual Studio and Xamarin. We’ll also talk about how to maximize code sharing and reuse existing .NET libraries.

At the end of the webinar, you’ll have the skills you need to create your first iOS and Android apps in C# with Xamarin in Visual Studio.

Wednesday, March 11
11:30 AM – 12:30 PM IST


All registrants will receive a copy of the webinar, so please feel free to register even if you can’t attend.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 23, 2015

Adding Real-world Context with Estimote Beacons and Stickers


It’s no secret that iBeacons have created a buzz in the development community. Leveraging these Bluetooth Smart devices enables developers to add contextual awareness to their mobile apps with just a few lines of code. iBeacons were everywhere at Evolve 2014, including at the forefront of the Evolve Quest scavenger hunt and the conference mini-hacks, as well as taking the main stage for an in-depth session.

sticker_bikeEstimote, a leader in the iBeacon space, recently introduced Estimote Stickers, a low-powered device to go alongside their traditional beacons. Stickers can be attached to almost anything and turn any everyday item into a “nearable” – a smart object that can transmit data about its location, motion, temperature, and environment to nearby apps and devices. Today, we’re pleased to announce the Estimote SDK for iOS, available on the Xamarin Component Store, enabling developers to easily detect Beacons and Estimote Stickers with a beautiful C# API that includes events and async/await support.

Detecting Nearables

Nearables have a new, simplified API. Each Nearable has a specific NearableType that can be used to detect, for example, Car, Dog, or Bike. You can decide to range for a specific type or all nearby Nearable devices.

Let’s see how easy it is to get up and running with Nearables by scanning for all Nearables that are close by.

Install the Estimote SDK for iOS

The very first task is to set up a new Xamarin.iOS project and add the Estimote SDK for iOS from the component store.


In addition to the SDK, you must specify NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription in your Info.plst file with a description that will be prompted to your users, since iBeacons use CoreLocation functionality.

Setting Up App ID

When you log in to your Estimote Cloud, you are able to manage all of your Beacons and Stickers in addition to creating API keys for your mobile apps. Once you have an app set up in the Estimote Cloud, you can config the app in your AppDelegate’s OnFinishedLaunching method:

Config.SetupAppID ("<appId from cloud>", "<appToken from cloud>");

While not required, it’s recommended to set up your app ID so that the SDK can now communicate with the Estimote Cloud to pull in unique attributes.

Ranging Nearables

Using the new NearableManager you can easily range for Nearables by subscribing to the RangedNearables event.

NearableManager manager;
public override void ViewDidLoad ()
  base.ViewDidLoad ();
  manager = new NearableManager ();
  manager.RangedNearables += (sender, e) => {
    //Nearables detected, load into TableView or pop up alert
    new UIAlertView("Nearables Found", "Just found: " + e.Nearables.Length + " nearables.", null, "OK").Show();
  //Specify the type of Nearable to range for. In this instance return All types.
  manager.StartRanging (NearableType.All);

Estimote Nearables Detected

The real power of Nearables is the additional attributes that are received when they are detected, such as their temperature, orientation, acceleration, and more. As an example, you could easily use these attributes to detect a Bike Nearable in motion for over 45 minutes and prompt your user to perhaps take a break.

NearableManager nearableManager;
public override void ViewDidLoad ()
  var identifier = "94064be7a9d7c189"; //Identifier ranged earlier
  var durationThreshold = 45 * 60; //45 minutes
  nearableManager = new NearableManager ();
  nearableManager.RangedNearable += (sender, e) => {
    var bike = e.Nearable;
    if(bike.IsMoving && bike.CurrentMotionStateDuration > durationThreshold) {
      Console.WriteLine("Bike is moving and has been in motion for over 45 minutes!");

Triggers and Rules

In addition to ranging and monitoring Nearables, there is an advanced trigger system in the Estimote SDK that enables you to specify several rules that would trigger a notification. Let’s say you want to be notified every time a Nearable changes orientation and is laid down in a horizontal position. You would simply create a OrientationRule and use the TriggerManager to wait for the Nearable’s state to change.

TriggerManager triggerManager;
public override void ViewDidLoad ()
  var rule = OrientationRule.OrientationEquals (NearableOrientation.Horizontal, NearableType.Shoe);
  var trigger = new Trigger (new Rule[]{ rule }, "TriggerId");
  triggerManager = new TriggerManager ();
  triggerManager.StartMonitoring (trigger);
  triggerManager.ChangedState += HandleTriggerChangedState;
  triggerManager.ChangedState += (sender, e) => {
    Console.Log("Shoe nearable has been placed horizontal");

More complex rules can be configured that are based on DateTime, temperature, proximity, and more.

Enhanced C# Beacon API

Xamarin.iOS has been able to detect iBeacons from any vendor since the feature was introduced in iOS 7 in CoreLocation. However, the Estimote SDK greatly simplifies the tasks of requesting and a simplified API for ranging and monitoring for beacons. In addition, if you are using Estimote Beacons you can tap into advanced features, such as their accelerometer.


Learn More

The Estimote SDK for iOS has plenty of great samples for both Nearables and Beacons for you to start out with, including a full Getting Started Guide. In addition, Estimote has SDK reference documentation and a developer portal with more information.

If you are interested in adding iBeacon functionality to your Xamarin.Android apps, be sure to check the component store for multiple libraries that you can take advantage of.

Discuss this post on the Xamarin Forums.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 19, 2015

Code Sharing Strategies for iOS & Mac


I fell in love with the Xamarin approach to mobile development because sharing code across platforms provided me with huge productivity gains when developing apps. With Xamarin you can share an average of 75% of app code across all mobile platforms and in this blog post, I’m going to give you some strategies to help you share even more code between iOS and OS X. If you’ve recently developed an app for iPhone or iPad using the traditional approach (sans Xamarin.Forms),  you might be surprised to learn how much code you can share between iOS and OS X. With the Mac platform becoming increasingly popular, there’s never been a better time to consider if your apps could benefit from targeting a new platform. Let’s learn some tips and tricks for sharing more code between the platform all in the context of C#.


General Code Sharing Strategies

It’s common knowledge that both iOS and OS X share a common architecture, which results in a great code sharing story. Many classes are compatible on both platforms without modification and with the recent release of the Unified API, we’ve made it even easier to share code between OS X and iOS.

Before we get started on linking all of our existing Xamarin.iOS code in a new Xamarin.Mac project, we need to first look at what we should share and what should remain platform dependent. The most common architectural pattern for iOS and OS X development is the Model View Controller (MVC) pattern. This increases the amount of code reuse in our app as many of the models and controllers will still be relevant regardless of the underlying platform.

Conditional Compilation (Shimming)

Sharing our view code is a little more involved, but is possible with a couple of techniques used by Apple in apps such as Keynote. Your existing iOS apps will be using the UIKit namespace, which is the framework that provides the window and view architecture needed to manage your app’s user interface. Here you will find labels, buttons, colors and other classes that you’ll build your app’s UI with. UIKit is only available for iOS, which means any code utilizing this framework will not run on the Mac without some modification. Let’s take a look at the simple sample problem of sharing colors between platforms.


var xamarinBlue = UIColor.FromRGB(0.26f, 0.83f, 0.31f);


var xamarinBlue = NSColor.FromCalibratedRgba(0.26f, 0.83f, 0.31f, 1f);

The above example is fairly consistent with what I find when looking at customers’ projects. With a little bit of trickery, we can share colors between platforms. Apple calls this “shimming” but you might know it as “conditional compilation”.

public class Color
 #if __MAC__
 public static NSColor FromRGB(nfloat r, nfloat g, nfloat b)
 return NSColor.FromCalibratedRgba(r, g, b, 1f);
 #if __IOS__
 public static UIColor FromRGB(nfloat r, nfloat g, nfloat b)
 return UIColor.FromRGB(r,g,b);

Now in both our iOS and OS X app, we can use the following to create our blue color.

var xamarinBlue = Color.FromRGB(0.26f, 0.83f, 0.31f);

If this is running on iOS, it will return a UIColor and on OS X we will get an NSColor. This is an approach I apply in many areas of UIKit and AppKit. You could for example extend this to UIImage and NSImage.

public static CGImage ToCGImage(string imageName)
 #if __MAC__
 return NSImage.ImageNamed(imageName).CGImage;
 #if __IOS__
 return UIImage.FromFile(imageName).CGImage;

Sharing Your UI with CALayers

If you want to maximize your code sharing, then you might want to investigate using CALayers. UIViews are built on CALayers, which can be accessed by using the Layer property of the UIView. The benefit of using CALayers over UIView is that CALayers can very easily be ported to OS X and there is no performance loss over using UIViews or NSViews. Apple’s Keynote canvas uses CALayers which allows them to share over 1m LOC between OS X and iOS.

In the example below, I’ve inherited from a CALayer and overridden the DrawInContext method to get the view setup. I set the background color, using my shimming method, to be purple. I then override the HitTest, which allows me to respond to touch or click events. In this sample, I want to change the background color of the layer every time the user interacts with it. Despite being a basic example, this code works on both iOS and OS X without any modification.

public class ColorChanger : CALayer
 public override void DrawInContext(CGContext ctx)
   BackgroundColor = Color.FromRGB(0.65f, 0.22f, 0.72f).CGColor;
   count = 0;
   this.Contents = Image.ToCGImage("xamagon.png");
 public override CALayer HitTest(CGPoint p)
   switch (count)
     case 0:
       BackgroundColor = BackgroundColor = Color.FromRGB(0.2f, 0.52f, 0.89f).CGColor;
     case 1:
       BackgroundColor = BackgroundColor = Color.FromRGB(0.26f, 0.83f, 0.31f).CGColor;
     case 2:
       BackgroundColor = BackgroundColor = Color.FromRGB(0.65f, 0.22f, 0.72f).CGColor;
       count = 0;
  return base.HitTest(p);
 int count = 0;


With Xamarin, you’ve always been able to share approximately 75% of your code between the different platforms, and now with the above tips you can share even more. If you’re looking for basic drawing between platforms, you may find Frank Krueger’s CrossGraphics library useful, as it allows for drawing graphics on Android, iOS, Mac, Windows, and ASP.Net using .Net.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 18, 2015

Xamarin App Video Spotlight: Curse Inc.


At Xamarin Evolve 2014, I had the opportunity to speak with Xamarin customer Curse, a multimedia technology company that builds websites and software for gamers. With 50 million users on their websites and 6 million users on their desktop client, Curse turned to Xamarin to help them build out Mac, Android, and iOS apps for their new product, Curse Voice.

Watch the video below to get a better understanding of how the Curse team was able to take their existing Windows code and get their innovative Curse Voice apps up and running quickly on Mac, iOS, and Android with Xamarin.

Learn More

Try out Curse Voice, from Curse, here.

To get started developing with the Xamarin platform, check out our developer documentation, or get live online training with Xamarin University.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 17, 2015

StepCounter Gets in Shape


Last year we announced the release of My StepCounter for iOS. Since then, the iOS landscape has changed considerably – HealthKit was announced, two new iPhones have been introduced, and the iPad now supports My StepCounter AppIcon the same API for CoreMotion as the iPhone.

The original app was designed purely with the iPhone 5s in mind, as this was the only supported hardware available at the time. With an increase in the number of devices that support the step counting API, I thought it was time to make an update to ensure the app works perfectly on these new devices.

While updating the app, I opted to migrate the user interface from Apple’s older Xib format to a single Storyboard. With this change, you’re now able to visualize how My StepCounter will look from within both Xamarin Studio and Visual Studio. The new approach is great for developers using Visual Studio, as they can minimize the amount of time interacting with Xcode on their Mac build host.


Not only does My StepCounter now support Storyboards, a number of images have been replaced with custom views drawn using code generated from PaintCode. The new change has cut down the number of artwork assets the app needs to ship with, and thus reduces the final binary size.

The benefit of this is huge, as it means the app looks great on any screen size without the binary size bloating from additional images. One of my favorite things about using a tool like PaintCode is that the control is live rendered within our storyboard designer so you can instantly see how your App will look in the designer without having to deploy to the simulator or device.

A few extra little additions to the app include integration with Xamarin Insights, a new share option so you can tweet or post your step count, and improved animations across the entire app.

All of the code is up on GitHub for you to download and explore today.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 13, 2015

Xamarin Contest: Give Us The Gist Of It!


When developing, having the right snippets of code handy can give you back a huge part of your day. In this contest, we want you to give us the (GitHub) Gist of your favorite snippets to help your fellow Xamarin developers write amazing mobile apps even faster!

How to Enter:

  1. Create a Gist on GitHub with your favorite code snippet
  2. Tweet your Gist link and name of what your snippet does with hashtags #XamarinGist & #Xamarin
  3. Post your Gist to to this Forum thread
  4. Bonus points: Link a simple sample project that demonstrates your snippet

Need help with a Gist? Click here! Need a Gist template? Try this one:
Snippet Name: iOS Colors
Platform(s): Xamarin.iOS
Function: Hex value to UIColor


public static UIColor FromHex(this string hexValue)
int colValue = int.Parse (hexValue,
return UIColor.FromRGB(
 (((float)((colValue & 0xFF0000) >> 16))/255.0f),
 (((float)((colValue & 0xFF00) >> 8))/255.0f),
 (((float)(colValue & 0xFF))/255.0f));

Example Use:

//Set the text color of the label to 39FF3F.
lblTextResult.TextColor = "39FF3F".FromHex ();

Prize: Exclusive long sleeve Xamarin t-shirt!

5 entries will be chosen at random, so the more snippets you submit,
the better your chances of winning

All submissions must be made by Monday, February 23rd at 12pm EST. We will evaluate each snippet based on concept, code quality, and originality. A valid entry consists of a tweet, forum post, and the Gist of your Snippet. All submissions must be unique. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up. There is no purchase necessary to enter the Give Us The Gist of It Contest!

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 12, 2015

Creating Your First WatchKit App


A new release of Xamarin’s Apple WatchKit support is now available for download, including initial support for the Xamarin iOS Designer. This post walks you through steps to create your first Watch Kit app (described in more detail in our WatchKit getting started guide).

File > New Watch App

Start with a new or existing iOS app, then add a Watch App. Xamarin Studio automatically creates both required projects: a Watch App and a Watch Extension.

Reference the Watch Extension

Before you can use the iOS Designer, or deploy and test in the iOS Simulator, reference the Watch Extension from your iOS app; and reference the Watch App from the Watch Extension.

Don’t forget to set the Bundle Identifiers correctly in each Info.plist.

Design the Watch UI

Double-click to open the Interface.storyboard in the iOS Designer.

Drag a Label and a Button onto the default InterfaceController. Don’t forget to give them a Name in the Properties pane (eg. myLabel and myButton).

Double-click on the button in the Designer to create a handler for when it’s pressed. Press enter to place the method in the code.

Just Add Code

Add the following code to the InterfaceController.cs file, which updates the label each time the button is pressed:

int clickCount = 0;

partial void myButton_Activated (WatchKit.WKInterfaceButton sender)
    var msg = String.Format("Clicked {0} times", ++clickCount);

Test in the Simulator

Ensure the Watch Extension project is set to be the start-up project, then select an iPhone 6 simulator and start debugging. Tip: use Bezel to see the simulator rendered inside an Apple Watch frame.


If you don’t see the simulated watch screen, select Hardware > External Displays in the iOS Simulator.

Video Walkthrough

You can also see the above steps on getting started with WatchKit in action in this short video:

Try it out today!

You can download our WatchKit Preview installers from the Xamarin developer portal (make sure you also have Xcode 6.2 beta 5 from Apple). Start with the WatchKit Preview guides and WatchKit samples.

Discuss this blog post in the Xamarin Forums.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone