Home > Back-end >  Why is only the second of two labels in a xaml page updating when I use a timer
Why is only the second of two labels in a xaml page updating when I use a timer

Time:01-19

I have an app I am using only for Android that has two labels. They are both representations of a countdown in different formats only. When I manually updated the labels by a button press the calculation of the time remaining in each label updated. I have now added a System.Timers.Timer which is set to update both labels simultaneously; however, only the second (coded) label is updated, whichever I put as the second in the code. This now also the case for when I press the button. What am I missing? The relevant code is as follows:

public MainPage()
        {
            InitializeComponent();
            t.Interval = 1000;
            t.Elapsed  = t_Tick;
            t.AutoReset = true;
            t.Enabled = true;
            calc(DateTime.Now);
        }
        private void OKbtnClick(object sender, EventArgs e)
        {
            calc(DateTime.Now);
        }
        public void calc(DateTime dt)
        {
            TimeSpan timeSpan = departure.Subtract(dt);
            opt = String.Format("Days: {0:N0}", timeSpan.TotalDays);
            opt  = String.Format("\nHours: {0:N0}", timeSpan.TotalHours);
            opt  = String.Format("\nMinutes: {0:N0}", timeSpan.TotalMinutes);
            opt  = String.Format("\nSeconds: {0:N0}", timeSpan.TotalSeconds);
            txtOutput.Text = opt;
            txtCountdown.Text = timeSpan.ToString(@"d\:hh\:mm\:ss");
        }
        private void t_Tick(object sender, ElapsedEventArgs e)
        {
            calc(e.SignalTime);
        }

CodePudding user response:

Please put your code in Device.BeginInvokeOnMainThread:

     public void calc(DateTime dt)
    {
        System.DateTime departure = new System.DateTime(2022, 2, 2, 22, 15, 0);

        TimeSpan timeSpan = departure.Subtract(dt);
        opt = String.Format("Days: {0:N0}", timeSpan.TotalDays);
        opt  = String.Format("\nHours: {0:N0}", timeSpan.TotalHours);
        opt  = String.Format("\nMinutes: {0:N0}", timeSpan.TotalMinutes);
        opt  = String.Format("\nSeconds: {0:N0}", timeSpan.TotalSeconds);
        

        Device.BeginInvokeOnMainThread(() => {
            txtOutput.Text = opt;

            txtCountdown.Text = timeSpan.ToString(@"d\:hh\:mm\:ss");
        });
    }
  •  Tags:  
  • Related