Xamarin.Forms: Content Page for XAML Controls

Step 1

Create a Xamarin.Forms project with Portable Class Library (PCL) as discussed in my previous article.

Step 2

Now right click on the PCL project and Add > New Item,

new

Inside the Cross-Platform, select Forms XAML Page and name it MainPage and click OK.

Forms

Step 3

Now in App.cs file, we call this MainPage inside the App constructor.

code

Step 4

In the MainPage.xaml, let's add Text Label and a Button with click event.

Complete Code

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              x:Class="HelloXamarin.MainPage">  
  5.   <ContentPage.Content>  
  6.     <StackLayout Padding="20">  
  7.       <Label x:Name="msg" Text="Hello World" FontSize="40"></Label>  
  8.     <Button Text="Click Me" BackgroundColor="Red" TextColor="White" Clicked="OnBtnClick"></Button>  
  9.     </StackLayout>  
  10.   </ContentPage.Content>  
  11. </ContentPage>  
Step 5

In the code behind MainPage.xaml.cs, we add click event of button,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. using Xamarin.Forms;  
  8.   
  9. namespace HelloXamarin  
  10. {  
  11.     public partial class MainPage : ContentPage  
  12.     {  
  13.         public MainPage()  
  14.         {  
  15.             InitializeComponent();  
  16.         }  
  17.         public void OnBtnClick(object o, EventArgs e)  
  18.         {  
  19.             msg.Text = "This is Xamarin Forms Content Page";  
  20.         }  
  21.     }  
  22. }  
Step 6

Now run the application in your Android emulator or Windows devices. When you click on button, you see the output as,

output
Ebook Download
View all
Learn
View all