Yes. You can use User Controls for this. You can Use XAML or code only. I'll explain the XAML way.
Just add a new XAML Page and change the root type from ContentPage
to StackLayout
. The root type can be every other layout or control. You have to decide what fits best.
MyControl.xaml
<?xml version="1.0" encoding="utf-8" ?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App6.MyControl">
<Label Text="{Binding Name}" />
<Label Text="{Binding Age}" />
<Label Text="{Binding CatAmount}" />
</StackLayout>
We bind the properties Name, Age, CatAmount
to three different labels. We assume, that the BindingContext
of this control is an object of type PersonData
(see below).
In your Code behind, you have to change the type as well.
MyControl.xaml.cs
public partial class MyControl : StackLayout
{
public MyControl()
{
InitializeComponent();
}
}
In your page, you have to add a new namespace (e.g. local
that points to you assembly, e.g. App6
or MyApp.Whatever
). Then you can use it via local:MyControl
. In our example control, we bind the BindingContext
to Person
, wich is a Property of our Page's BindingContext, that is (in our case) the page itself. If your control is in a sub namespace, you have to change the namespace part accordingly.
Page2.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App6;assembly=App6"
x:Class="App6.Page2">
<local:MyControl BindingContext="{Binding Person}"></local:MyControl>
</ContentPage>
Page2.xaml.cs
public class PersonData
{
public string Name { get; set; }
public int Age { get; set; }
public int CatAmount { get; set; }
}
public partial class Page2 : ContentPage
{
public PersonData Person { get; set; }
public Page2()
{
Person = new PersonData {Age = 28, Name = "Sven", CatAmount = 2};
InitializeComponent();
BindingContext = this;
}
}
And in your mentioned Scenario, you can simply inherit from ContentPage
and add your common elements and use you inherited Page as base class of your pages.
TemplatedPage - Xamarin.Forms 2.1
With Xamarin.Forms 2.1 they introduced TemplatedPage
. You find the example here: http://xfcomplete.net/general/2016/01/20/control-templates/ . The LoginView
example with the ContentPresenter
fits your scenario exactly.