Currently in my application, I have a RelayCommand
which calls an action which starts a Timer
. I have a separate command which the calls the Dispose()
method to get rid of/release the timer. This all sits in the ViewModel counterpart of the project.
Using the MVVM pattern, how would I dispose of this Timer
upon closing the window, as well as carrying out the regular/default operation of closing the window?
I am also using the MVVM-Light toolkit, if this is of any help.
An example of my current solution is shown below:
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();
//Would a 'Closing +=' event be called here?
}
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
, which I am assuming is the same as what you posted. Will give this a go now. Cheers. – Pemberton