Xamarin Forms

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 to the shared project.

MyPage.png

Step 2) Set MyPage as main page.

Open App.cs in the Shared project and replace the GetMainPage method with the following:

public static Page GetMainPage()
{
  return 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.

EnableXCC.png

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="Yellow"
    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:

result.android.png

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

result.wp.png

Last edited Jun 26, 2014 at 3:00 PM by kozw, version 5