-
Notifications
You must be signed in to change notification settings - Fork 16
How to: 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.
Create a new Blank App project (Xamarin.Forms.Shared) and add a new Forms Xaml Page named MyPage.xaml to the shared project.
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();
}
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.
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.
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>
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:
(c) 2013-2016 First Floor Software