NewCode82
NewCode82

Reputation: 31

WPF How to Update UI Correctly

I should refresh a 10 of controls on the Home page every 100ms. Right now I'm using the DispatcherTimer. The interface refreshes but occasionally some component gets stuck at the previous value. Here is the code I am using:

private void Timer_Tick(object? sender, EventArgs e)
    {
        try
        {
            var data = driver.GetData();
            if (data != null)
            {
                if (data.Krd3Front.TempOk)
                {
                    TxtTempFront1.Foreground = Brushes.Lime;
                    TxtPvTempBarFront.Foreground = Brushes.Lime;
                    TxtTempFront2.Foreground = Brushes.Lime;
                }
                else
                {
                    TxtTempFront1.Foreground = Brushes.Red;
                    TxtPvTempBarFront.Foreground = Brushes.Red;
                    TxtTempFront2.Foreground = Brushes.Red;
                }
                if (data.Krd3Rear.TempOk)
                {
                    TxtTempRear1.Foreground = Brushes.Lime;
                    TxtPvTempBarRear.Foreground = Brushes.Lime;
                    TxtTempRear2.Foreground = Brushes.Lime;
                }
                else
                {
                    TxtTempRear1.Foreground = Brushes.Red;
                    TxtPvTempBarRear.Foreground = Brushes.Red;
                    TxtTempRear2.Foreground = Brushes.Red;
                }
                TxtPvTempBarFront.Text = data.Krd3Front.Pv.ToString();
                TxtPvTempBarRear.Text = data.Krd3Rear.Pv.ToString();
                ProgressBarFront.Progress = data.Krd3Front.Pv;
                ProgressBarRear.Progress = data.Krd3Rear.Pv;
                ProgresVacuum.Progress = data.AsblyLine.FdbkVacuum;
                ProgresGas.Progress = data.AsblyLine.FdbkGas;
                ProgresSealing.Progress = data.AsblyLine.FdbkSealing;
                TxtActVacuum.Text = data.AsblyLine.FdbkActVacuum.ToString();
                TxtActGas.Text = data.AsblyLine.FdbkActGas.ToString();
                TxtActSealing.Text = data.AsblyLine.FdbkActSealing.ToString();
            }
        }
        catch (Exception ex)
        {
            App.logger.Error(ex.Message);
        }

I think it's not the correct way to update the UI in this case. Can you give me some advice on this?

I expected the DispatcherTimer to be the solution to my problem.

Upvotes: 0

Views: 101

Answers (0)

Related Questions