我创建了一个具有 ObservableCollection 的 WPF 视图模型。viewmodel 绑定到 usercontrol 并且 usercontrol 在 tabitem 中加载。
当我删除用户控件表单 Tabitem。视图模型正在处理,但 ObservableCollection 仍保留在内存中(我没有在视图中使用该集合)。我使用 ANTS 分析器对此进行了测试。
以下是来自 ANTS 分析器的对象保留图。
视图模型代码如下:
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; }
}
}
字段类代码
public class Field
{
public string PersonName { get; set; }
}
用户控制代码是
public partial class UserControl4 : UserControl
{
public UserControl4()
{
InitializeComponent();
}
private void UserControl_Unloaded(object sender, RoutedEventArgs e)
{
UserControl4ViewModel userControl4ViewModel =(UserControl4ViewModel) this.DataContext;
userControl4ViewModel.DisposeContent();
}
}
usercontrol XAML 视图代码是
<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>
请帮我从内存中处理 Observable 集合。
——阿伦