Disposal of a timer inside the ViewModel when closing the main window

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(); //Would a 'Closing +=' event be called here? } 
+1
source share
2 answers

Closing windows may or may not dispose of your viewing model, depending on how you register it. One approach would be tied to Loaded / Unloaded events from the view and do the work there:

View:

XMLNS: i = "CLR Names: System.Windows.Interactivity; assembly = System.Windows.Interactivity"

 <i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <i:InvokeCommandAction Command="{Binding PageLoadedCommand}"/> </i:EventTrigger> <i:EventTrigger EventName="Unloaded"> <i:InvokeCommandAction Command="{Binding PageUnLoadedCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> 

ViewModel:

 public RelayCommand PageUnLoadedCommand { get; private set; } ... PageUnLoadedCommand = new RelayCommand(() => OnPageUnLoadedCommand()); 

...

  private void OnPageUnLoadedCommand() { //Unsubscribe and dispose here } 
+2
source

You can add a destructor for the ViewModel as shown below

 ~public MainViewModel() { dispatchTimer.Dispose(); } 
0
source

Source: https://habr.com/ru/post/1210104/


All Articles