RazrMan
RazrMan

Reputation: 163

Xamarin.forms how to show ActivityIndicator in every Page?

I made a ActivityIndicator like this: <ActivityIndicator IsVisible="{Binding IsBusy}" IsRunning="{Binding IsBusy}"></ActivityIndicator> which is depending of IsBusy parameter . My question is how to add this ActivityIndicator on every page on center and be transparent?

Upvotes: 2

Views: 2140

Answers (1)

Leo Zhu
Leo Zhu

Reputation: 14981

You could create a LoadingPage with ActivityIndicator,using ControlTemplate.

For example:

1.create a LoadingPage:

public class LoadingPage: ContentPage
{
    public static readonly BindableProperty RootViewModelProperty =
       BindableProperty.Create(
           "RootViewModel", typeof(object), typeof(LoadingPage),
           defaultValue: default(object));

    public object RootViewModel
    {
        get { return (object)GetValue(RootViewModelProperty); }
        set { SetValue(RootViewModelProperty, value); }
    }
}

2.define a ControlTemplate in your App.xaml:

<Application.Resources>
    <ResourceDictionary>
      <ControlTemplate x:Key="LoaderViewTemplate">
        <AbsoluteLayout Padding = "0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
           <ContentPresenter AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All"/>
           <ActivityIndicator Color= "White" IsRunning= "{TemplateBinding RootViewModel.IsBusy}" AbsoluteLayout.LayoutBounds=".5,.5,100,100" AbsoluteLayout.LayoutFlags="PositionProportional" />                   
        </AbsoluteLayout>
      </ControlTemplate>
    </ResourceDictionary>
</Application.Resources>
 

3.using in a contentpage,let the page extends the LoadingPage:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyPage: LoadingPage
{
    public MyPage()
    {
        InitializeComponent();
        ViewModel viewmodel = new ViewModel () { IsBusy = true };// your viewmodel must have property IsBusy
        BindingContext = viewmodel;
    }
}

MyPage.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<local:LoadingPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         xmlns:local="clr-namespace:EntryCa"
         RootViewModel="{Binding}"
         ControlTemplate="{StaticResource LoaderViewTemplate}"
         x:Class="EntryCa.MyPage">
   <ContentPage.Content>
     <StackLayout>
        <Label Text="Welcome to Xamarin.Forms!"
            VerticalOptions="Start" 
            HorizontalOptions="Start" />
     </StackLayout>
   </ContentPage.Content>
</local:LoadingPage>

Upvotes: 4

Related Questions