gpt4 book ai didi

c# - Xamarin.Forms C#属性未在Device.StartTimer中更新

转载 作者:行者123 更新时间:2023-12-03 10:22:16 28 4
gpt4 key购买 nike

我想创建一个倒计时所选时间的应用程序。但是我有一个奇怪的问题,我不知道自己在做什么错。

这是我的计时器,每次选择器的属性更改时都会调用它。当我选择时间时,代码仅删除1秒钟,然后不再更新。

Picker.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == TimePicker.TimeProperty.PropertyName)
{
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
clockViewModel.SelectedTime = Picker.Time.Subtract(TimeSpan.FromSeconds(1));
return true;
});
}
};

我还尝试打印一个值,该值不断更新:
public int i = 0;

private void StartTimer()
{
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
clockViewModel.SelectedTime = Picker.Time.Subtract(TimeSpan.FromSeconds(1));
label.Text = i;
i++;
return true;
});
}

值(value)不断增加,所以我确定它正在做某事。

这是我的模型 View :
public class ClockViewModel : BaseViewModel
{
private TimeSpan selectedTime;

public TimeSpan SelectedTime
{
get => selectedTime;
set
{
selectedTime = value;
NotifyPropertyChanged();
}
}
}

有人知道我在这里做错了吗?

最佳答案

计时器在其他线程中运行。如果要在UI所在的主线程上运行某些内容,则必须使用Device.BeginInvokeOnMainThread()方法。像这样:

Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
Device.BeginInvokeOnMainThread (() =>
{
clockViewModel.SelectedTime = Picker.Time.Subtract(TimeSpan.FromSeconds(1));
label.Text = i;
});

i++;
return true;
});

关于c# - Xamarin.Forms C#属性未在Device.StartTimer中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53325536/

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