Home > Enterprise >  Multiple Timers in ListView buttons WPF
Multiple Timers in ListView buttons WPF

Time:07-22

I've been struggling with the problem of adding a Timer to a Button in Listview for some time. I have about 100 buttons in ListView. I would like everyone to measure 15 minutes to the end after clicking. So far I have written something like this but is not working:

private readonly DispatcherTimer timer = new DispatcherTimer();            
private DateTime Timers_end;

private void Button_ListView_Click(object sender, EventArgs e)
    {
        var BTN = sender as Button;          

        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick  = delegate 
        {
            var now = DateTime.Now;

            Timers_end = now.AddMinutes(15);

            BTN.Content = (Timers_end - now).ToString(@"hh\:mm\:ss"); 

        };           
        timer.Start();            
    } 

I would like each button to work independently.

CodePudding user response:

it can work in this way:

    private Timer timer = null;
    private DateTime Timers_end;
    private void Button_ListView_Click(object sender, RoutedEventArgs e)
    {
        var BTN = sender as Button;
        var time = Timers_end;
        timer = new Timer();
        timer.Interval = 1000;
        time = DateTime.Now.AddMinutes(15);
        timer.Elapsed  = delegate
        {
            var now = DateTime.Now;
            BTN.Dispatcher.Invoke(() => { BTN.Content = (time - now).ToString(@"hh\:mm\:ss"); });
        };
        timer.Start();
    }

CodePudding user response:

You need an instance of DispatcherTimer for each button. You can store these instances on a Dictionary. I think the code below can make the job

class TimerInfo
{ 
    public DispatcherTimer timer { get; set; }
    public DateTime Timers_end { get; set; }
}

Dictionary<Button, TimerInfo> timers = new Dictionary<Button, TimerInfo>();

private void Button_ListView_Click(object sender, EventArgs e)
{
    var BTN = (Button)sender;

    if (!timers.TryGetValue(BTN, out TimerInfo timer))
    {
        timer = new TimerInfo { timer = new DispatcherTimer() };
        timers[BTN] = timer;
    }

    timer.timer.Interval = TimeSpan.FromSeconds(1);
    timer.timer.Tick  = delegate
    {
        var now = DateTime.Now;

        timer.Timers_end = now.AddMinutes(15);

        BTN.Content = (timer.Timers_end - now).ToString(@"hh\:mm\:ss");

    };
    timer.timer.Start();
}
  • Related