如何处理 UI 线程更新 C# Xamarin.Froms

我已经开发了一个在两个不同时间更新我的 UI 的应用程序,让我解释一下。有一个按钮网格,使用OnTimedEvent和Timer类每 2 秒更新一次。但是,我有一个可以在用户点击时更新的分数。我的困境来自于网格更新时整个 UI 更新的形式。我知道为什么会发生这种情况,或者至少我相信我知道,但我不知道如何解决这个问题。欢迎反馈,输入,解决方案。对任何 UI 线程都是全新的。在继续之前,我必须允许用户在 2 秒内进行选择,但是用户可以在这 2 秒内多次运行计数,但在 2 秒的威胁计数结束之前它不会更新计数。我已经用尽了我所有的想法!提前致谢。


 private void SetTimer()

 {

   // Create a timer with a two second interval.

   aTimer = new System.Timers.Timer(2000);

   // Hook up the Elapsed event for the timer. 

   aTimer.Elapsed += OnTimedEvent;

   aTimer.AutoReset = true;

   aTimer.Enabled = true;

}

private void OnTimedEvent(Object source, ElapsedEventArgs e)

{

   Device.BeginInvokeOnMainThread(() =>

   {

   /*

   ...

   */

               

   for (int i = 0; i < gridSizeToInt; i++)

   {

        NewGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });

        NewGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

        for (int j = 1; j <= gridSizeToInt; j++)

        {

            //rand num generator code

           Button newBtn;

           NewGrid.Children.Add(newBtn = new Button{BackgroundColor = ColorArray[temp1]}, i, j);

           newBtn.Clicked += Button_Click;

           clickCountLabel.Text = "Click Count: " + ClickCount;

        }

    }

   

  });

}


喵喵时光机
浏览 218回答 1
1回答

慕丝7291255

但它不会更新计数,直到 2 秒的威胁计数结束因为您正在更新OnTimedEvent. 它每两秒触发一次。您应该将代码放在按钮单击事件中。例如:&nbsp; &nbsp; private void Button_Click(object sender, EventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; ClickCount++;&nbsp; &nbsp; &nbsp; &nbsp; clickCountLabel.Text = "Click Count: " + ClickCount;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP