gpt4 book ai didi

C# Xamarin 计时器类不更新 View

转载 作者:行者123 更新时间:2023-11-30 15:52:42 24 4
gpt4 key购买 nike

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using Xamarin.Forms;

namespace TimerTest
{
public partial class MainPage : ContentPage
{
Label label;
int i = 0;
private static System.Timers.Timer aTimer;

public MainPage()
{
InitializeComponent();

label = new Label
{
Text = ""+i,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
this.Content = label;
SetTimer();
//this.Content = label;


}
public 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 async void OnTimedEvent(Object source, ElapsedEventArgs e)
{
i++;
label.Text = ""+i;
//this.Content = label;
}
}
}

我关注了Microsoft's但是,当尝试实际实现它时,屏幕上不会更新任何内容。

下面我在 Xamarin.Forms 中设置了一个简单的程序,它应该将 label 更新为每 2 秒的任何 i 的计数>,但是,屏幕刚好位于 0(label 启动的位置)。

有没有人知道我做错了什么以及如何解决我的问题?

提前致谢!

最佳答案

您不在 UI 线程上,因为 Timer 回调在后台线程上,在这种情况下更新 UI 元素时使用 Device.BeginInvokeOnMainThread:

因此,当在回调中更新您的 label 实例时,请执行以下操作:

Device.BeginInvokeOnMainThread(() => label.Text = "" +i;);

If I were to update the text and update another element, would I just place a , after label.Text = ""+1or would I have to have a whole other line replicated,

提供给 BeginInvokeOnMainThread 的参数是一个 Action,因此您可以仅使用一个“ block ”在 UI 线程上执行所需的代码:

Device.BeginInvokeOnMainThread(() =>
{
...;
...;
...;
});

或者:

void UIThreadAction()
{
...;
...;
...;
}
Device.BeginInvokeOnMainThread(UIThreadAction);

关于C# Xamarin 计时器类不更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53789432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com