简体   繁体   中英

WPF C# Checkbox controlling a timer

I'm stuck here. I have a checkbox. When checked, start timer. When unchecked stop timer. I can use some help here. I have tried checked, unchecked, and click events. Nothing is stopping the timer. It just keeps running...

Xaml: (has all three events just for show)

<CheckBox x:Name="CbAutoRefresh" Grid.Row="1" ClipToBounds="True" HorizontalAlignment="Left" Content="Enable Auto Refresh" Margin="10,0,0,0" Width="150" Click="CbAutoRefresh_Click" Checked="CbAutoRefresh_Checked" Unchecked="CbAutoRefresh_Unchecked" />

C#: (all three attempts)

private void CbAutoRefresh_Click(object sender, RoutedEventArgs e)
{

    var aTimer = new Timer();
    if (CbAutoRefresh.IsChecked == true)
    {
        //start a timer:

        aTimer.Elapsed += OnTimedEvent;
        aTimer.Interval = 60000;
        aTimer.Enabled = true;
    }
    else
    {
        aTimer.Enabled = false;
    }
}

private void CbAutoRefresh_Checked(object sender, RoutedEventArgs e)
{
    //start a timer:
    var aTimer = new Timer();
    aTimer.Elapsed += OnTimedEvent;
    aTimer.Interval = 60000;
    aTimer.Enabled = true;
}

private void CbAutoRefresh_Unchecked(object sender, RoutedEventArgs e)
{
    var aTimer = new Timer {Enabled = false};
}

I even tried this, which was mention at Stack Overflow

<CheckBox Checked="CheckBoxChanged" Unchecked="CheckBoxChanged"/>

private void CheckBoxChanged(object sender, RoutedEventArgs e)
{
  MessageBox.Show("Eureka, it changed!");
}

Remove the statement

var aTimer = new Timer(); 

from withing the clicked handler. move it to the constructor or some function run just once during the object's lifetime. Use Timer's Start() & Stop() methods to start and stop the timer.

don't create a new Timer on every event. Declare 1 timer in Window object (window field/property), initialize it in constructor and work with it in any event handlers. At the moment you are running multiple timers

<CheckBox x:Name="CbAutoRefresh" Checked="CheckBoxChanged" Unchecked="CheckBoxChanged"/>
public class MyWindow()
{
   private Timer _t;
   public MyWindow()
   {
      InitializeComponent();
      _t = new Timer();
      _t.Elapsed += OnTimedEvent;
      _t.Interval = 60000;
   }

   private void CheckBoxChanged(object sender, RoutedEventArgs e)
   {
      _t.Enabled = CbAutoRefresh.IsChecked;
   }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM