TabItem close ViewModel

Apr 2, 2014 at 10:03 AM
Hi,
in my application i use the TabControl where items are added on button click:
<catel:TabControl ItemsSource="{Binding RecordItems}" SelectedItem="{Binding SelectedRecItem}">
 <catel:TabControl.ContentTemplate>
  <DataTemplate>
   <views:RecordTabView DataContext="{Binding}"/>
  </DataTemplate>
 </catel:TabControl.ContentTemplate>
 <catel:TabControl.ItemTemplate>
  <DataTemplate>
   <Grid>
    <Grid.ColumnDefinitions>
     <ColumnDefinition Width="*" />
     <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <ContentControl Content="{Binding Title}" />
    <telerik:RadButton Grid.Column="1" Command="{Binding CloseCommand}"/>
   </Grid>
  </DataTemplate>
 </catel:TabControl.ItemTemplate>
</catel:TabControl>
On every button click I add a new RecordTabViewModel to my ItemsSource.
This works perfect everything is displayed correctly. Also the CloseCommand is fired on every ViewModel.
So when I want to close a tab I remove the tab from the collection. The problem here is that the viewmodel is still alive (checked with timer which counts up). I have tried to close the viewmodel manually, but this also does not work. Am I missing here something?

Regards Markus
Coordinator
Apr 2, 2014 at 10:30 AM
If you are saying that the view models are not closed when being unloaded, please provide a repro, then we will take a look at it.
Apr 2, 2014 at 11:07 AM
Hi,
here you can download:

Dropbox

Regards Markus
Coordinator
Apr 5, 2014 at 3:41 PM
I have checked the example. The reason is that you don't stop timers. In .NET, everything is garbage collected. This means that when you close the view model, it doesn't mean it's out of memory at that time.

What I recommend is that you override these methods:
  • Initialize
  • Close
like the example below:

        protected override void Initialize()
        {
            base.Initialize();

            _timer.Elapsed += TimElapsed;
            _timer.Start();
        }

        protected override void Close()
        {
            _timer.Elapsed -= TimElapsed;
            _timer.Stop();

            base.Close();
        }
Then the view model will be garbage collected at some point by the .NET runtime and Catel as soon as it can be disposed.
Marked as answer by Rawukal on 4/13/2014 at 11:00 PM
Apr 14, 2014 at 6:00 AM
Ok,
I thought this is done by closing the view model.

Thank you for your help!

Regards Markus