Today I'm going to show you how to add dynamic pages in Xamarin .This is important when we need to change our views dynamically. Trick that we using here is Content views in Xamarin as sub pages not ContentPages.
First we create Content Page called MainPage and 2 content views called Page1 and Page2 That pages looks like this
MainPage.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" x:Class="DynamicPages.MainPage"> <StackLayout Padding="20"> <StackLayout Orientation="Horizontal" HorizontalOptions="Center" > <Button Text="Page1" Clicked="onPage1ButtonClick"/> <Button Text="Page2" Clicked="onPage2ButtonClick"/> </StackLayout> <StackLayout HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" x:Name="DynamicPageView"> </StackLayout> </StackLayout> </ContentPage>
In Main page I added 2 Buttons and Stack Layout named "DynamicPageView" .
Page1.xaml
<?xml version="1.0" encoding="utf-8" ?> <ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="DynamicPages.Page1"> <StackLayout> <Label Font="20" Text="This is page 1"/> </StackLayout> </ContentView>
Page2.xaml
<?xml version="1.0" encoding="utf-8" ?> <ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="DynamicPages.Page2"> <StackLayout> <Label Font="20" Text="This is page 2"/> </StackLayout> </ContentView>
In Page1 and Page2 we use Content views not Content Pages and we added only Labels on each pages
MainPage.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace DynamicPages { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } public void onPage1ButtonClick(object o, EventArgs e) { DynamicPageView.Children.Clear(); DynamicPageView.Children.Add(new Page1()); } public void onPage2ButtonClick(object o, EventArgs e) { DynamicPageView.Children.Clear(); DynamicPageView.Children.Add(new Page2()); } } }
In MainPage.cs we add 2 functions for button clicks
DynamicPageView.Children.Clear(); DynamicPageView.Children.Add(new Page1());
In here we add children to our StackLayout in MainPage.xaml .It's important to clear Children before add new one.otherwise it will add redundant pages.
Final views look like this
Important :- we have to use Content views as Page 1 and Page 2
If you have any question feel free to post a comment bellow.Thank you very much see you soon.Happy Hunting