I have created a WPF viewmodel which have an ObservableCollection. The viewmodel is bound to usercontrol and the usercontrol is loaded in tabitem.
When I am removing the user control form Tabitem. The viewmodel is getting disposed but the ObservableCollection remains in memory ( I have not used the collection in the view) . I tested this using ANTS profiler.
Following is the object retention graph from the ANTS profiler.
The viewmodel code is as below:
namespace TestControl
{
class UserControl4ViewModel : INotifyPropertyChanged
{
public UserControl4ViewModel()
{
fieldList = new ObservableCollection<Field>();
fieldList.Add(new Field() { PersonName = "Test1" });
fieldList.Add(new Field() { PersonName = "Test2" });
fieldList.Add(new Field() { PersonName = "Test3" });
fieldList.Add(new Field() { PersonName = "Test4" });
}
public ObservableCollection<Field> FieldList
{
get
{
return fieldList;
}
set
{
fieldList = value;
OnPropertyChanged("FieldList");
}
}
private ObservableCollection<Field> fieldList;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public void DisposeContent()
{
if (fieldList != null)
{
fieldList.Clear();
}
fieldList = null;
}
}
public class Field
{
public string PersonName { get; set; }
}
}
Field Class Code
public class Field
{
public string PersonName { get; set; }
}
The user control code is
public partial class UserControl4 : UserControl
{
public UserControl4()
{
InitializeComponent();
}
private void UserControl_Unloaded(object sender, RoutedEventArgs e)
{
UserControl4ViewModel userControl4ViewModel =(UserControl4ViewModel) this.DataContext;
userControl4ViewModel.DisposeContent();
}
}
The usercontrol XAML view code is
<UserControl x:Class="TestControl.UserControl4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestControl"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" Unloaded="UserControl_Unloaded">
<UserControl.DataContext>
<local:UserControl4ViewModel>
</local:UserControl4ViewModel>
</UserControl.DataContext>
<Grid>
</Grid>
</UserControl>
Please help me disposing Observable collection from the memory.
--Arun