Creating User Controls In Xamarin Forms

In my earlier blog about accordion user control, I missed explaining about the whole need and purpose of user controls.The concept of User Controls is not new, and exists in many different platforms including ASP.NET, XAML for Windows and Windows Phone as well as Web Forms. Basically the idea is to create a collection of controls that will be reused as a single control throughout the application.The User Control exposes properties allowing you to reuse the control while allowing each instance of the control to have different settings, layout, or behavior.

Another benefit of user control is that we can bundle them separately in a project and can use them as a custom control in any other project /application and because of this very reason I personally prefer to create user controls for any repetitive UI I need in any of my applications.

As per Xamarin documentation, the view which should be mostly used to create user control should be ContentView. In an earlier article I explained that to create an accordion and in this article I will be creating a very commonly required user control ‘Form Containers’ which looks something like the following MockUp:
ContainerMockUp
Here we have a Container with Title with one background and content with different background, giving the screen a feel like Form control. Let's create similar UI in Xamarin Forms.

Firstly, create a new project in Xamarin/Visual Studio (see this article for steps) and add new ContentView XAML page. Add the following XAML to the control page:

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentView xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              x:Class="FormContainer.MyContainer">  
  5.   <ContentView.Content>  
  6.     <Grid RowSpacing="0">  
  7.       <Grid.RowDefinitions>  
  8.         <RowDefinition Height="60" />  
  9.         <RowDefinition Height="*" />  
  10.       </Grid.RowDefinitions>  
  11.       <Grid.ColumnDefinitions>  
  12.         <ColumnDefinition Width="5" />  
  13.         <ColumnDefinition Width="*" />  
  14.         <ColumnDefinition Width="5" />  
  15.       </Grid.ColumnDefinitions>  
  16.       <Frame Grid.Row="0" Grid.Column="1" x:Name="HeaderFrame" OutlineColor="Black" HasShadow="False">  
  17.         <Label x:Name="HeaderLabel" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />  
  18.       </Frame>  
  19.       <Frame Grid.Row="1" Grid.Column="1" x:Name="ContentFrame" OutlineColor="Black" HasShadow="False">  
  20.       </Frame>  
  21.     </Grid>  
  22.   </ContentView.Content>  
  23. </ContentView>  

In the above code we are creating a Grid with 2 Rows (one for header and second for content) and 3 columns (first and last is for giving the spacing). In the first row we are putting the Frame with Header label and in second row we are putting a blank frame for the content of the control.
As we can’t create properties of the control in XAML, so write the following code in code behind of control to create it’s properties:

  1. using Xamarin.Forms;  
  2. namespace FormContainer  
  3. {  
  4.     [ContentProperty("ContainerContent")]  
  5.     public partial class MyContainer : ContentView  
  6.     {  
  7.    
  8.         public MyContainer()  
  9.         {  
  10.             InitializeComponent();  
  11.         }  
  12.   
  13.         #region Properties  
  14.    
  15.         public View ContainerContent  
  16.         {  
  17.             get { return ContentFrame.Content; }  
  18.             set { ContentFrame.Content = value; }  
  19.         }  
  20.         public Color ContentBackgroundColor  
  21.         {  
  22.             get { return ContentFrame.BackgroundColor; }  
  23.             set { ContentFrame.BackgroundColor = value;}  
  24.         }  
  25.         public string HeaderText  
  26.         { get { return HeaderLabel.Text; } set { HeaderLabel.Text = value; } }  
  27.         public Color HeaderTextColor  
  28.         { get { return HeaderLabel.TextColor; } set { HeaderLabel.TextColor = value; } }  
  29.         public Color HeaderBackGroundColor  
  30.         { get { return HeaderFrame.BackgroundColor; } set { HeaderFrame.BackgroundColor = value; } }  
  31.         #endregion  
  32.     }  
  33. }  

As you can see from the above code the control will have five properties, their names are self-explanatory for their requirements like one for ContainerContent, another for Content Background Color and so on. This completes the code of the user control.

As an example on how to use the control in XAML lets create a new XAML ContentPage and add the following code in that to create two forms one for Login and one for SignUp:

  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.              xmlns:ctrl="clr-namespace:FormContainer;assembly=FormContainer"  
  5.              x:Class="FormContainer.XamlExample" Title="XAML Example" Padding="0,10,0,0">  
  6.   <ContentPage.Resources>  
  7.     <ResourceDictionary>  
  8.       <Style TargetType="Button">  
  9.         <Setter Property="BorderRadius" Value="10" />  
  10.         <Setter Property="BorderWidth" Value="2" />  
  11.         <Setter Property="WidthRequest" Value="100" />  
  12.         <Setter Property="HeightRequest" Value="30" />  
  13.         <Setter Property="HorizontalOptions"  Value="Center" />  
  14.         <Setter Property="VerticalOptions"    Value="Center" />  
  15.         <Setter Property= Value="Medium" />  
  16.         <Setter Property="TextColor" Value="Red" />  
  17.       </Style>  
  18.     </ResourceDictionary>  
  19.   </ContentPage.Resources>  
  20.   <ContentPage.Content>  
  21.     <StackLayout Spacing="0" >  
  22.       <ctrl:MyContainer HeaderText="Login (XAML)" HeaderTextColor="White" HeaderBackGroundColor="Black" ContentBackgroundColor="#F0F0F0">  
  23.         <ctrl:MyContainer.ContainerContent>  
  24.           <StackLayout>  
  25.             <Entry Placeholder="User Name" />  
  26.             <Entry Placeholder="Password" />  
  27.             <Button Text="Login" />  
  28.           </StackLayout>  
  29.         </ctrl:MyContainer.ContainerContent>  
  30.       </ctrl:MyContainer>  
  31.       <BoxView  HeightRequest = "10"  />  
  32.       <ctrl:MyContainer HeaderText="Sign Up (XAML)" HeaderTextColor="White" HeaderBackGroundColor="Black" ContentBackgroundColor="#F0F0F0">  
  33.         <ctrl:MyContainer.ContainerContent>  
  34.           <StackLayout>  
  35.             <Entry Placeholder="First Name" />  
  36.             <Entry Placeholder="Last Name" />  
  37.             <Entry Placeholder="User Name" />  
  38.             <Entry Placeholder="Email" />  
  39.             <Entry Placeholder="Password" />  
  40.             <Entry Placeholder="Confirm Password" />  
  41.             <Button Text="Sign Up" />  
  42.           </StackLayout>  
  43.         </ctrl:MyContainer.ContainerContent>  
  44.       </ctrl:MyContainer>  
  45.     </StackLayout>  
  46.   </ContentPage.Content>  
  47. </ContentPage>  
This is how the output will look on an iOS simulator:

FormContaineriOSExXaml

In the same way we can use this control for only showing data, let's create one example for that but this time using C# code. So create a new code only content Page and add the following code to it :

  1. using Xamarin.Forms;  
  2.    
  3. namespace FormContainer  
  4. {  
  5.     public class CodeEaxmple : ContentPage  
  6.     {  
  7.         public CodeEaxmple()  
  8.         {  
  9.             Padding = new Thickness(0,10,0,10);  
  10.             Title = "Code Example";  
  11.             var vContentStack = new StackLayout  
  12.             {  
  13.                 Children = {  
  14.                     new Label { Text = "Name : S Ravi Kumar", TextColor=Color.Red },  
  15.                      new Label { Text = "Place : India", TextColor=Color.Red },  
  16.                       new Label { Text = "Twitter : @srkrathore", TextColor=Color.Red },  
  17.                        new Label { Text = "Blog : http://err2solution.com/", TextColor=Color.Red },  
  18.                 }  
  19.             };  
  20.             var vFormContainer = new MyContainer() {  
  21.                 HeaderText = "My Details (Code)",  
  22.                 HeaderTextColor = Color.Red,  
  23.                 HeaderBackGroundColor= Color.Gray,  
  24.                 ContentBackgroundColor = Color.White,  
  25.                 ContainerContent = vContentStack  
  26.             };  
  27.             Content = vFormContainer;  
  28.         }  
  29.     }  
  30. }  
This is how the output will look on an iOS simulator:

FormContaineriOSExCode
I have just scratched the surface of user control creation in Xamarin Forms, you can dig deeper into it buy executing the code for Android & Windows.The source code of sample application containing this user control and pages using the control can be downloaded from GitHub.

Let me know if I have missed anything or you have any queries/suggestions.

Read more articles on Xamarin:


Similar Articles