Skip to content
This repository has been archived by the owner on Sep 2, 2021. It is now read-only.

How to: Xamarin Forms

Koen Zwikstra edited this page Feb 9, 2015 · 4 revisions

Learn how to enable conditional compilation in a shared Xamarin Forms project.

Note: this tutorial assumes you have Xamarin 3.0 installed, and are licensed to use it in Visual Studio.

Step 1) Create project and shared MyPage.xaml

Create a new Blank App project (Xamarin.Forms.Shared) and add a new Forms Xaml Page named MyPage.xaml to the shared project.

Step 2) Set MyPage as main page.

Open App.cs in the Shared project and replace the App() constructor with the following:

public App ()
{
  // The root page of your application
  MainPage = new MyPage();
}

Step 3) Enable XCC

Open the solution context menu and select Manage NuGet Package for Solution.... Search for xcc and install the XAML Conditional Compilation NuGet package in all projects.

Step 4) Create XML attributes

Open MyPage.xaml in the Shared project and add the following attributes to the root element

<ContentPage ...
  xmlns:android="condition:__ANDROID__"
  xmlns:ios="condition:__IOS__"
  xmlns:wp="condition:WINDOWS_PHONE"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="android ios wp"
  mc:ProcessContent="android:* ios:* wp:*">
 ..
</ContentPage>

The xmlns:android, xmlns:ios and xmlns:wp attributes define the namespaces for conditional compiled XML elements and attributes. The condition:xxx syntax is used to associate the XML namespace with the actual compilation symbols defined for the project. Elements and attributes prefixed with android: are included when the project is compiled with symbol _ANDROID_. The prefix ios: ensures the element or attribute is emitted only when the _IOS_ symbol is defined. And finally the prefix wp: ensures the element or attribute is emitted only when the WINDOWS_PHONE symbol is defined.

The mc:Ignorable attribute ensure the new xmlns prefixes are ignored by designers and compilers. The mc:ProcessContent attribute enables Intellisense inside conditional regions.

Step 5) Start using conditional compilation

With the conditional compilation namespaces in place we can now replace the ContentPage content with the following XAML

<StackLayout VerticalOptions="FillAndExpand">
  <Label Text="Always visible" VerticalOptions="Center" HorizontalOptions="Center"
    android:TextColor="Green"
    ios:TextColor="Blue"
    wp:TextColor="Red" />
  <android:Label Text="Android only" VerticalOptions="Center" HorizontalOptions="Center"/>
  <ios:Label Text="iOS only" VerticalOptions="Center" HorizontalOptions="Center"/>
  <wp:Label Text="Windows Phone only" VerticalOptions="Center"
    HorizontalOptions="Center"/>
</StackLayout>

Step 6) Run

Compile and run the Android project. The following content is shown:

Compile and run the iOS project. The following content is shown:

Run the Windows Phone project and the following content is shown: