Xamarin.Forms有一个用于启动计时器的API,您可能会发现它对此有用,在此处记录.
Device.StartTimer (TimeSpan.FromSeconds(10), () => { // If you want to update UI, make sure its on the on the main thread. // Otherwise, you can remove the BeginInvokeOnMainThread Device.BeginInvokeOnMainThread(() => methodRunPeriodically()); return shouldRunAgain; });
根据上述问题中的代码,您将确保:
您的userdata对象实现IPropertyChange,如下所示:
//Other usings skipped for brevity ... ... using System.ComponentModel; using System.Runtime.CompilerServices; // This is a simple user class that // implements the IPropertyChange interface. public class DemoUser : INotifyPropertyChanged { // These fields hold the values for the public properties. private string userName = string.Empty; private string phoneNumber = string.Empty; public event PropertyChangedEventHandler PropertyChanged; // This method is called by the Set accessor of each property. // The CallerMemberName attribute that is applied to the optional propertyName // parameter causes the property name of the caller to be substituted as an argument. private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public DemoUser() { } public string Id { get; set; } public string UserName { get { return this.userName; } set { if (value != this.userName) { this.userName = value; NotifyPropertyChanged(); } } } public string PhoneNumber { get { return this.phoneNumber; } set { if (value != this.phoneNumber) { this.phoneNumber = value; NotifyPropertyChanged(); } } } }
在您的ContentPage中,然后尝试以下操作(我稍微修改了上面的其他代码):
public class UserPage : ContentPage { private DemoUser demoUser; private int intervalInSeconds; public UserPage() { //Assuming this is a XAML Page.... InitializeComponent(); } public UserPage(DemoUser demoUser, int intervalInSeconds = 10) : this() { this.demoUser = demoUser; this.intervalInSeconds = intervalInSeconds; this.BindingContext = this.demoUser; Device.StartTimer(TimeSpan.FromSeconds(this.intervalInSeconds), () => { Device.BeginInvokeOnMainThread(() => refreshDemoUser()); return true; }); } private async void refreshDemoUser() { this.demoUser = await getDemoUserById(this.demoUser.Id); } }