从ViewModel </t>处理ObservableCollection <t>

时间:2015-02-03 13:23:29

标签: c# wpf mvvm .net-4.0 ants

我创建了一个具有ObservableCollection的WPF视图模型。 viewmodel绑定到usercontrol,usercontrol以tabitem加载。

当我删除用户控件表单Tabitem时。视图模型正在处理,但ObservableCollection仍保留在内存中(我没有在视图中使用该集合)。我使用ANTS分析器测试了这个。

以下是ANTS分析器的对象保留图。

enter image description here

viewmodel代码如下:

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集合。

- 阿伦

0 个答案:

没有答案
相关问题