There is currently a RelayCommand in my application that invokes an action that triggers Timer . I have a separate command that calls the Dispose() method to get rid of / release the timer. All this is in the ViewModel of the project.
Using the MVVM pattern, how can I get rid of this Timer after closing the window, and also perform a regular / standard window closing operation?
I also use the MVVM-Light toolkit if that helps.
The following is an example of my current solution:
ViewModel
private static Timer dispatchTimer; public MainViewModel() { this.StartTimerCommand = new RelayCommand(this.StartTimerAction); this.StopTimerCommand = new RelayCommand(this.StopTimerAction); } public RelayCommand StartTimerCommand { get; private set; } public RelayCommand StopTimerCommand { get; private set; } private void StartTimerAction() { dispatchTimer = new Timer(new TimerCallback(this.IgnoreThis), null, 0, 15); } private void StopTimerAction() { dispatchTimer.Dispose(); }
View (xaml)
.... Height="896" Width="1109" DataContext="{Binding Main, Source={StaticResource Locator}}"> <Grid x:Name="mainGrid" Width="Auto" Height="Auto"> <Button x:Name="startTimerButton" Content="Start Timer" Command="{Binding StartTimerCommand}"/> <Button x:Name="stopTimerButton" Content="Stop Timer" Command="{Binding StopTimerCommand}"/> </Grid> </Window>
View (code behind)
public MainWindow() { this.InitializeComponent();
source share