I am making a countdown list where each item contains a datetime to count down to and each listview datatemplate needs to show this countdown in real time. What is the best and most optimized way to make a list that counts down to a specified time using a SfListView?
Thanks,
Bryson
Hi Bryson,
We have prepared a sample
demonstrating a time left countdown list implementation using SfListView
control, which you can review in the attached reference. This solution
showcases dynamic countdown tracking with real-time updates. Please let us know
if you need further assistance.
|
public class CountdownItem : INotifyPropertyChanged { // Gets or sets the target date and time for the countdown public DateTime TargetDateTime { get; set; }
// Gets or sets the display name for the target duration public string? TargetTime { get; set; }
// Gets or sets the remaining time display value. // Triggers PropertyChanged event on update. private string? remainingTime; public string? RemainingTime { get { return remainingTime; } set { remainingTime = value; OnPropertyChanged(nameof(RemainingTime));
} } } |
|
public class CountdownViewModel : INotifyPropertyChanged { public ObservableCollection<CountdownItem> CountdownItems { get; set; } private System.Timers.Timer timer;
public CountdownViewModel() { // Initializes countdown items and starts the update timer CountdownItems = new ObservableCollection<CountdownItem> { new CountdownItem { TargetTime="10 Seconds", TargetDateTime = DateTime.Now.AddSeconds(10) },// Countdown for 10 seconds new CountdownItem { TargetTime="5 Minutes", TargetDateTime = DateTime.Now.AddMinutes(5) }, // Countdown for 5 minutes new CountdownItem { TargetTime="10 Minutes", TargetDateTime = DateTime.Now.AddMinutes(10) }, // Countdown for 10 minutes new CountdownItem { TargetTime="1 Hour", TargetDateTime = DateTime.Now.AddHours(1) }, // Countdown for 1 hour new CountdownItem { TargetTime="1 Day", TargetDateTime = DateTime.Now.AddDays(1) } // Countdown for 1 day };
StartTimer(); }
private void StartTimer() { timer = new System.Timers.Timer(1000); // 1 second interval timer.Elapsed += TimerElapsed;
// start a timer timer.Start(); }
// Timer callback that updates all countdown items' remaining times private void TimerElapsed(object sender, ElapsedEventArgs e) { foreach (var item in CountdownItems) { // calculate remaining time TimeSpan timeLeft = item.TargetDateTime - DateTime.Now; item.RemainingTime = timeLeft > TimeSpan.Zero ? timeLeft.ToString(@"hh\:mm\:ss") : "Time's up!"; } } } |
Displays countdowns in a ListView:
|
<syncfusion:SfListView ItemsSource="{Binding CountdownItems}"> <DataTemplate> <Grid> <Label Text="{Binding TargetTime}"/> <!-- Display name --> <Label Text="{Binding RemainingTime}"/> <!-- Dynamic countdown --> </Grid> </DataTemplate> </syncfusion:SfListView> |
Regards,
Sowntharya J.