Is it Possible to access progress bar from first page to second page in xamarin forms?

Viewed 263

Is it possible to do this:

I have a progress bar in first page and i set it IsVisible = false

i created a Dependency method in first page

[assembly:Dependency(typeof(page.view.FirstPage))]
public interface Progress
{
    void StartProgress();
}

public partial class FirstPage : ContentPage
{
    public FirstPage()
    {

    }

    public void StartProgress()
    {
        //do progression here
          and set Progress bar 
           IsVisible = true;
    }
}

and access the method from FirstPage to SecondPage

example i have a Button in second page

private void Onpress(s, e)
{
    DependencyService.Get<Progress>().StartProgress();
    Navigation.PopToRootAsync();
}

then the progress bar in first page will start running.... But my code doesnt work

2 Answers

Yes, you can use MessagingCenter for this. In your first page, subscribe a message:

      public FirstPage()
       {
         MessagingCenter.Subscribe<SecondPage>(this, "StartProgress", (sender) =>
          {
           StartProgress();
          }); 
        }
    
        public void StartProgress()
        {
            //do progression here
            //and set Progress bar 
               IsVisible = true;
        }

And in your second page send the message:

 private void Onpress(s, e)
{
   MessagingCenter.Send(this, "StartProgress");
    Navigation.PopToRootAsync();
}

You can find documentation in here.

Is it possible to start the progress bar in page1 from page2?

Yes, in addition to the answer below you can use Commands to do this

Page1.Xaml

<StackLayout VerticalOptions="CenterAndExpand">
    <ProgressBar
        x:Name="ProgressBar1"
        Progress="1"
        ProgressColor="Red"
        IsVisible="False" />
    <Button Clicked="Button_OnClicked" Text="Click here"/>
</StackLayout>

Page1.Cs

    public static Command StartProgressCommand;
    public Page1()
    {
        InitializeComponent();
        StartProgressCommand = new Command(() => { ProgressBar1.IsVisible = true; });
    }
    private void Button_OnClicked(object sender, EventArgs e)
    {
       Navigation.PushModalAsync( new Page2());
    }

Page2.Xaml

    <StackLayout VerticalOptions="EndAndExpand">
        <Button Clicked="Button_OnClicked"  Text="Start Progress"/>
    </StackLayout>

Page2.Cs

   private void Button_OnClicked(object sender, EventArgs e)
    {
        Page1.StartProgressCommand.Execute(null);
        Navigation.PopModalAsync(true);
    }

Note: It's better to use Mvvm pattern to do this instead of this way

Related