Xamarin.Forms Quickstart

PDF for offline use:
Related Articles:
Related Samples:

Let us know how you feel about this.


0/250
Thanks for the feedback!

last updated: 2016-12

This walkthrough demonstrates how to create an application that translates an alphanumeric phone number entered by the user into a numeric phone number, and that calls the number. The final application is shown below:

Create the Phoneword application as follows:

  1. In the Applications folder, or from Spotlight, launch Xamarin Studio. This opens the start page:

  2. In Xamarin Studio click New Solution... to create a new project:

  3. In the Choose a template for your new project dialog, click Multiplatform > App, select the Forms App template, and click the Next button:

  4. In the Configure your Forms app dialog, name the new app Phoneword, ensure that the Use Portable Class Library radio button is selected, ensure that the Use XAML for user interface files checkbox is selected, and click the Next button:

  5. In the Configure your new project dialog, leave the Solution and Project names set to Phoneword, choose a suitable location for the project, and click the Create button to create the project:

  6. In the Solution Pad, select the Phoneword project, right-click and select Add > New File...:

  7. In the New File dialog, select Forms > Forms ContentPage Xaml, name the new file MainPage, and click the New button. This will add a page named MainPage to the project:

  8. In the Solution Pad, double-click MainPage.xaml to open it:

  9. In MainPage.xaml, remove all of the template code and replace it with the following code. This code declaratively defines the user interface for the page:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="Phoneword.MainPage">
         <ContentPage.Padding>
            <OnPlatform x:TypeArguments="Thickness"
                        iOS="20, 40, 20, 20"
                        Android="20, 20, 20, 20"
                        WinPhone="20, 20, 20, 20" />
         </ContentPage.Padding>
        <ContentPage.Content>
            <StackLayout VerticalOptions="FillAndExpand"
                         HorizontalOptions="FillAndExpand"
                         Orientation="Vertical"
                         Spacing="15">
                <Label Text="Enter a Phoneword:" />
                <Entry x:Name="phoneNumberText" Text="1-855-XAMARIN" />
                <Button x:Name="translateButon" Text="Translate" Clicked="OnTranslate" />
                <Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" />
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>

    Save the changes to MainPage.xaml by choosing File > Save (or by pressing ⌘ + S), and close the file.

  10. In the Solution Pad, double-click MainPage.xaml.cs to open it:

  11. In MainPage.xaml.cs, remove all of the template code and replace it with the following code. The OnTranslate and OnCall methods will be executed in response to the Translate and Call buttons being clicked on the user interface, respectively:

    using System;
    using Xamarin.Forms;
    
    namespace Phoneword
    {
        public partial class MainPage : ContentPage
        {
            string translatedNumber;
    
            public MainPage ()
            {
                InitializeComponent ();
            }
    
            void OnTranslate (object sender, EventArgs e)
            {
                translatedNumber = Core.PhonewordTranslator.ToNumber (phoneNumberText.Text);
                if (!string.IsNullOrWhiteSpace (translatedNumber)) {
                    callButton.IsEnabled = true;
                    callButton.Text = "Call " + translatedNumber;
                } else {
                    callButton.IsEnabled = false;
                    callButton.Text = "Call";
                }
            }
    
            async void OnCall (object sender, EventArgs e)
            {
                if (await this.DisplayAlert (
                        "Dial a Number",
                        "Would you like to call " + translatedNumber + "?",
                        "Yes",
                        "No")) {
                    var dialer = DependencyService.Get<IDialer> ();
                    if (dialer != null)
                        dialer.Dial (translatedNumber);
                }
            }
        }
    }

    Save the changes to MainPage.xaml.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  12. In the Solution Pad, double-click App.xaml.cs to open it:

  13. In App.xaml.cs, remove all of the template code and replace it with the following code. The App constructor sets the MainPage class as the page that will be displayed when the application starts:

    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    
    [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
    namespace Phoneword
    {
        public partial class App : Application
        {
            public App()
            {
                InitializeComponent();
                MainPage = new MainPage();
            }
    
            protected override void OnStart()
            {
                // Handle when your app starts
            }
    
            protected override void OnSleep()
            {
                // Handle when your app sleeps
            }
    
            protected override void OnResume()
            {
                // Handle when your app resumes
            }
        }
    }

    Save the changes to Phoneword.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  14. In the Solution Pad, select the Phoneword project, right-click and select Add > New File...:

  15. In the New File dialog, select General > Empty Class, name the new file PhoneTranslator, and click the New button:

  16. In PhoneTranslator.cs, remove all of the template code and replace it with the following code. This code will translate a phone word to a phone number:

    using System.Text;
    
    namespace Core
    {
        public static class PhonewordTranslator
        {
            public static string ToNumber(string raw)
            {
                if (string.IsNullOrWhiteSpace(raw))
                    return null;
    
                raw = raw.ToUpperInvariant();
    
                var newNumber = new StringBuilder();
                foreach (var c in raw)
                {
                    if (" -0123456789".Contains(c))
                        newNumber.Append(c);
                    else
                    {
                        var result = TranslateToNumber(c);
                        if (result != null)
                            newNumber.Append(result);
                        // Bad character?
                        else
                            return null;
                    }
                }
                return newNumber.ToString();
            }
    
            static bool Contains(this string keyString, char c)
            {
                return keyString.IndexOf(c) >= 0;
            }
    
            static readonly string[] digits = {
                "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
            };
    
            static int? TranslateToNumber(char c)
            {
                for (int i = 0; i < digits.Length; i++)
                {
                    if (digits[i].Contains(c))
                        return 2 + i;
                }
                return null;
            }
        }
    }

    Save the changes to PhoneTranslator.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  17. In the Solution Pad, select the Phoneword project, right-click and select Add > New File...:

  18. In the New File dialog, select General > Empty Interface, name the new file IDialer, and click the New button:

  19. In IDialer.cs, remove all of the template code and replace it with the following code. This code defines a Dial method that must be implemented on each platform to dial a translated phone number:

    namespace Phoneword
    {
        public interface IDialer
        {
            bool Dial(string number);
        }
    }

    Save the changes to IDialer.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

    ℹ️

    The common code for the application is now complete. Platform-specific phone dialer code will now be implemented as a DependencyService.

  20. In the Solution Pad, select the Phoneword.iOS project, right-click and select Add > New File...:

  21. In the New File dialog, select General > Empty Class, name the new file PhoneDialer, and click the New button:

  22. In PhoneDialer.cs, remove all of the template code and replace it with the following code. This code creates the Dial method that will be used on the iOS platform to dial a translated phone number:

    using Foundation;
    using Phoneword.iOS;
    using UIKit;
    using Xamarin.Forms;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.iOS
    {
        public class PhoneDialer : IDialer
        {
            public bool Dial(string number)
            {
                return UIApplication.SharedApplication.OpenUrl (
                    new NSUrl ("tel:" + number));
            }
        }
    }

    Save the changes to PhoneDialer.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  23. In the Solution Pad, select the Phoneword.Droid project, right-click and select Add > New File...:

  24. In the New File dialog, select General > Empty Class, name the new file PhoneDialer, and click the New button:

  25. In PhoneDialer.cs, remove all of the template code and replace it with the following code. This code creates the Dial method that will be used on the Android platform to dial a translated phone number:

    using Android.Content;
    using Android.Telephony;
    using Phoneword.Droid;
    using System.Linq;
    using Xamarin.Forms;
    using Uri = Android.Net.Uri;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.Droid
    {
        public class PhoneDialer : IDialer
        {
            public bool Dial(string number)
            {
                var context = Forms.Context;
                if (context == null)
                    return false;
    
                var intent = new Intent (Intent.ActionCall);
                intent.SetData (Uri.Parse ("tel:" + number));
    
                if (IsIntentAvailable (context, intent)) {
                    context.StartActivity (intent);
                    return true;
                }
    
                return false;
            }
    
            public static bool IsIntentAvailable(Context context, Intent intent)
            {
                var packageManager = context.PackageManager;
    
                var list = packageManager.QueryIntentServices (intent, 0)
                    .Union (packageManager.QueryIntentActivities (intent, 0));
    
                if (list.Any ())
                    return true;
    
                var manager = TelephonyManager.FromContext (context);
                return manager.PhoneType != PhoneType.None;
            }
        }
    }

    Save the changes to PhoneDialer.cs by choosing File > Save (or by pressing ⌘ + S), and close the file.

  26. In the Solution Pad, expand the Properties folder and double-click the AndroidManifest.xml file:

  27. In the Required permissions section, enable the CallPhone permission. This gives the application permission to place a phone call:

  28. Save the changes to AndroidManifest.xml by choosing File > Save (or by pressing ⌘ + S), and close the file.

  29. In Solution Pad, remove the PhonewordPage class from the Phoneword project. This page was automatically added when the project was created, and is no longer required.
  30. In Xamarin Studio, select the Build > Build All menu item (or press ⌘ + B). The application will build and a success message will appear in the Xamarin Studio toolbar.

  31. If there are errors, repeat the previous steps and correct any mistakes until the application builds successfully.

  32. In the Xamarin Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside the iOS Simulator:

    Note: phone calls are not supported in the iOS Simulator.

  33. In the Solution Pad, select the Phoneword.Droid project, right-click and select Set As Startup Project:

  34. In the Xamarin Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside an Android emulator:

    Note: phone calls are not supported in Android emulators.

  1. In the Start screen, launch Visual Studio. This opens the start page:

  2. In Visual Studio, click New Project... to create a new project:

  3. In the New Project dialog, click Cross-Platform, select the Blank Xaml App (Xamarin.Forms Portable) template, set the Name and Solution name to Phoneword, choose a suitable location for the project and click the OK button:

  4. In Solution Explorer, right-click on the Phoneword solution and select Manage NuGet Packages for Solution...:

  5. In the Manage Packages for Solution dialog, select the Updates tab, select the Xamarin.Forms package, and update the package to the latest stable release:

  6. In Solution Explorer, in the Phoneword project, double-click MainPage.xaml to open it:

  7. In MainPage.xaml, remove all of the template code and replace it with the following code. This code declaratively defines the user interface for the page:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="Phoneword.MainPage">
         <ContentPage.Padding>
            <OnPlatform x:TypeArguments="Thickness"
                        iOS="20, 40, 20, 20"
                        Android="20, 20, 20, 20"
                        WinPhone="20, 20, 20, 20" />
         </ContentPage.Padding>
        <ContentPage.Content>
            <StackLayout VerticalOptions="FillAndExpand"
                         HorizontalOptions="FillAndExpand"
                         Orientation="Vertical"
                         Spacing="15">
                <Label Text="Enter a Phoneword:" />
                <Entry x:Name="phoneNumberText" Text="1-855-XAMARIN" />
                <Button x:Name="translateButon" Text="Translate" Clicked="OnTranslate" />
                <Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" />
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>

    Save the changes to MainPage.xaml by pressing CTRL+S, and close the file.

  8. In Solution Explorer, expand MainPage.xaml and double-click MainPage.xaml.cs to open it:

  9. In MainPage.xaml.cs, remove all of the template code and replace it with the following code. The OnTranslate and OnCall methods will be executed in response to the Translate and Call buttons being clicked in the user interface, respectively:

    using System;
    using Xamarin.Forms;
    
    namespace Phoneword
    {
        public partial class MainPage : ContentPage
        {
            string translatedNumber;
    
            public MainPage ()
            {
                InitializeComponent ();
            }
    
            void OnTranslate (object sender, EventArgs e)
            {
                translatedNumber = Core.PhonewordTranslator.ToNumber (phoneNumberText.Text);
                if (!string.IsNullOrWhiteSpace (translatedNumber)) {
                    callButton.IsEnabled = true;
                    callButton.Text = "Call " + translatedNumber;
                } else {
                    callButton.IsEnabled = false;
                    callButton.Text = "Call";
                }
            }
    
            async void OnCall (object sender, EventArgs e)
            {
                if (await this.DisplayAlert (
                        "Dial a Number",
                        "Would you like to call " + translatedNumber + "?",
                        "Yes",
                        "No")) {
                    var dialer = DependencyService.Get<IDialer> ();
                    if (dialer != null)
                        dialer.Dial (translatedNumber);
                }
            }
        }
    }

    Save the changes to MainPage.xaml.cs by pressing CTRL+S, and close the file.

  10. In Solution Explorer, expand App.xaml and double-click App.xaml.cs to open it:

  11. In App.xaml.cs, remove all of the template code and replace it with the following code. The App constructor simply sets the MainPage class as the page that will be displayed when the application starts:

    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    
    [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
    namespace Phoneword
    {
        public partial class App : Application
        {
            public App()
            {
                InitializeComponent();
                MainPage = new MainPage();
            }
    
            protected override void OnStart()
            {
                // Handle when your app starts
            }
    
            protected override void OnSleep()
            {
                // Handle when your app sleeps
            }
    
            protected override void OnResume()
            {
                // Handle when your app resumes
            }
        }
    }

    Save the changes to App.xaml.cs by pressing CTRL+S, and close the file.

  12. In Solution Explorer, right click on the Phoneword project and select Add > New Item...:

  13. In the Add New Item dialog, select Visual C# > Code > Class, name the new file PhoneTranslator, and click the Add button:

  14. In PhoneTranslator.cs, remove all of the template code and replace it with the following code. This code will translate a phone word to a phone number:

    using System.Text;
    
    namespace Core
    {
        public static class PhonewordTranslator
        {
            public static string ToNumber(string raw)
            {
                if (string.IsNullOrWhiteSpace(raw))
                    return null;
    
                raw = raw.ToUpperInvariant();
    
                var newNumber = new StringBuilder();
                foreach (var c in raw)
                {
                    if (" -0123456789".Contains(c))
                        newNumber.Append(c);
                    else
                    {
                        var result = TranslateToNumber(c);
                        if (result != null)
                            newNumber.Append(result);
                        // Bad character?
                        else
                            return null;
                    }
                }
                return newNumber.ToString();
            }
    
            static bool Contains(this string keyString, char c)
            {
                return keyString.IndexOf(c) >= 0;
            }
    
            static readonly string[] digits = {
                "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
            };
    
            static int? TranslateToNumber(char c)
            {
                for (int i = 0; i < digits.Length; i++)
                {
                    if (digits[i].Contains(c))
                        return 2 + i;
                }
                return null;
            }
        }
    }

    Save the changes to PhoneTranslator.cs by pressing CTRL+S, and close the file.

  15. In Solution Explorer, right click on the Phoneword project and select Add > New Item...:

  16. In the Add New Item dialog, select Visual C# > Code > Interface, name the new file IDialer, and click the Add button:

  17. In IDialer.cs, remove all of the template code and replace it with the following code. This code defines a Dial method that must be implemented on each platform to dial a translated phone number:

    namespace Phoneword
    {
        public interface IDialer
        {
            bool Dial(string number);
        }
    }

    Save the changes to IDialer.cs by pressing CTRL+S, and close the file.

    ℹ️

    The common code for the application is now complete. Platform-specific phone dialer code will now be implemented as a DependencyService.

  18. In Solution Explorer, right click on the Phoneword.iOS project and select Add > New Item...:

  19. In the Add New Item dialog, select Apple > Code > Class, name the new file PhoneDialer, and click the Add button:

  20. In PhoneDialer.cs, remove all of the template code and replace it with the following code. This code creates the Dial method that will be used on the iOS platform to dial a translated phone number:

    using Foundation;
    using Phoneword.iOS;
    using UIKit;
    using Xamarin.Forms;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.iOS
    {
        public class PhoneDialer : IDialer
        {
            public bool Dial(string number)
            {
                return UIApplication.SharedApplication.OpenUrl (
                    new NSUrl ("tel:" + number));
            }
        }
    }

    Save the changes to PhoneDialer.cs by pressing CTRL+S, and close the file.

  21. In Solution Explorer, right click on the Phoneword.Droid project and select Add > New Item...:

  22. In the Add New Item dialog, select Visual C# > Android > Class, name the new file PhoneDialer, and click the Add button:

  23. In PhoneDialer.cs, remove all of the template code and replace it with the following code. This code creates the Dial method that will be used on the Android platform to dial a translated phone number:

    using Android.Content;
    using Android.Telephony;
    using Phoneword.Droid;
    using System.Linq;
    using Xamarin.Forms;
    using Uri = Android.Net.Uri;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.Droid
    {
        public class PhoneDialer : IDialer
        {
            public bool Dial(string number)
            {
                var context = Forms.Context;
                if (context == null)
                    return false;
    
                var intent = new Intent (Intent.ActionCall);
                intent.SetData (Uri.Parse ("tel:" + number));
    
                if (IsIntentAvailable (context, intent)) {
                    context.StartActivity (intent);
                    return true;
                }
    
                return false;
            }
    
            public static bool IsIntentAvailable(Context context, Intent intent)
            {
                var packageManager = context.PackageManager;
    
                var list = packageManager.QueryIntentServices (intent, 0)
                    .Union (packageManager.QueryIntentActivities (intent, 0));
    
                if (list.Any ())
                    return true;
    
                var manager = TelephonyManager.FromContext (context);
                return manager.PhoneType != PhoneType.None;
            }
        }
    }

    Save the changes to PhoneDialer.cs by pressing CTRL+S, and close the file.

  24. In Solution Explorer, in the Phoneword.Droid project, double-click Properties and select the Android Manifest tab:

  25. In the Required permissions section, enable the CALL_PHONE permission. This gives the application permission to place a phone call:

    Save the changes to the manifest by pressing CTRL+S, and close the file.

  26. In Solution Explorer, right click on the Phoneword.UWP project and select Add > New Item...:

  27. In the Add New Item dialog, select Visual C# > Code > Class, name the new file PhoneDialer, and click the Add button:

  28. In PhoneDialer.cs, remove all of the template code and replace it with the following code. This code creates the Dial method, and helper methods, that will be used on the Universal Windows Platform to dial a translated phone number:

    using Phoneword.UWP;
    using System;
    using System.Threading.Tasks;
    using Windows.ApplicationModel.Calls;
    using Windows.UI.Popups;
    using Xamarin.Forms;
    
    [assembly: Dependency(typeof(PhoneDialer))]
    namespace Phoneword.UWP
    {
        public class PhoneDialer : IDialer
        {
            bool dialled = false;
    
            public bool Dial(string number)
            {
                DialNumber(number);
                return dialled;
            }
    
            async void DialNumber(string number)
            {
                var phoneLine = await GetDefaultPhoneLineAsync();
                if (phoneLine != null)
                {
                    phoneLine.Dial(number, number);
                    dialled = true;
                }
                else
                {
                    var dialog = new MessageDialog("No line found to place the call");
                    await dialog.ShowAsync();
                    dialled = false;
                }
            }
    
            async Task<PhoneLine> GetDefaultPhoneLineAsync()
            {
                var phoneCallStore = await PhoneCallManager.RequestStoreAsync();
                var lineId = await phoneCallStore.GetDefaultLineAsync();
                return await PhoneLine.FromIdAsync(lineId);
            }
        }
    }

    Save the changes to PhoneDialer.cs by pressing CTRL+S, and close the file.

  29. In Solution Explorer, in the Phoneword.UWP project, right-click References, and select Add Reference...:

  30. In the Reference Manager dialog, select Universal Windows > Extensions > Windows Mobile Extensions for UWP, and click the OK button:

  31. In Solution Explorer, in the Phoneword.UWP project, double-click Package.appxmanifest:

  32. In the Capabilities page, enable the Phone Call capability. This gives the application permission to place a phone call:

    Save the changes to the manifest by pressing CTRL+S, and close the file.

  33. In Visual Studio, select the Build > Build Solution menu item (or press CTRL+SHIFT+B). The application will build and a success message will appear in the Visual Studio status bar:

    If there are errors, repeat the previous steps and correct any mistakes until the application builds successfully.

  34. In Solution Explorer, right click on the Phoneword.UWP project and select Set as StartUp Project:

  35. In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application:

  36. In Solution Explorer, right click on the Phoneword.Droid project and select Set as StartUp Project.

  37. In the Visual Studio toolbar, press the Start button (the triangular button that resembles a Play button) to launch the application inside the Android Simulator.
  38. If you have an iOS device and meet the Mac system requirements for Xamarin.Forms development, use a similar technique to deploy the app to the iOS device. Note: phone calls are not supported on all the simulators.

Congratulations on completing a Xamarin.Forms application. The next topic in this guide reviews the steps that were taken in this walkthrough in order to gain an understanding of the fundamentals of application development using Xamarin.Forms.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.