0

I'm new to xamarin forms. So therefore I have a trouble with UI updating. I'm using Device.BeginInvokeOnMainThread to update value on Dashboard. But it doesnt work. It updates value only with reload of the page:

public Dashboard ()
        {
            InitializeComponent ();
            Init();
        }

        public void Init()
        {
            Task.Run(async () =>
            {
                float speed = MainPage.acceleration;
                if (speed < 0)
                {
                    speed = speed * (-1);
                }
                Device.BeginInvokeOnMainThread(() =>
                {
                    Value.Text = speed.ToString();
                });
            });
        } 

2 Answers2

0

if you just want to do a one-time update, place it in OnAppearing()

protected override void OnAppearing() {

  base.OnAppearing();

  float speed = MainPage.acceleration;

  if (speed < 0)
  {
    speed = speed * (-1);
  }
  Value.Text = speed.ToString()
}
Jason
  • 86,222
  • 15
  • 131
  • 146
0

Jason has it right. The constructor only performs initialization of the page. OnAppearing is a page lifecycle event that fires just before the page becomes visible. It will only fire once the page is loaded into view, not when you leave the App and go back to it. If you want to handle leaving the App and coming back to it, you should look into App Lifecycle events. Check out Page lifecycle events in xamarin.forms.

A concise approach for testing this could include overriding each page and app lifecycle event. You can add breakpoints to the base call to see how things flow first hand.

cy-c
  • 855
  • 8
  • 8