我目前使用一个ContentControl中显示通过设置虚拟机,并使用这样的默认数据模板,我的看法:免费存储在ContentControl中使用
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:MyViewViewModel}">
<views:MyView />
</DataTemplate>
</UserControl.Resources>
<ContentControl Content="{Binding ContainerContent}"/>
这里是我的ContainerContent:
public ViewModelBase ContainerContent
{
get
{
return _containerContent;
}
set
{
if (_containerContent != null)
_containerContent.Cleanup();
_containerContent = value;
RaisePropertyChanged("ContainerContent");
}
}
我目前使用SimpleIoc通过服务定位器来加载视图模型:
ContainerContent = ServiceLocator.Current.GetInstance<MyViewViewModel>();
这很好,并正确显示我的视图和viewModel分配给内容。
不幸的是,当我想从我的ContentControl中删除视图(和视图模型)时,由于ViewModel,View和SimpleIoc之间的发布顺序,我的内存仍然被使用。视图有一段时间引用它认为这是定时由于在容器上
我目前使用的方法,以除去内容RaisePropertyCHange后的结合):
public void QuitCurrentContainerViewModel<T>() where T : class
{
ContainerContent = null;
Task.Factory.StartNew(() =>
{
if (/*!*/SimpleIoc.Default.ContainsCreated<T>())
{
SimpleIoc.Default.Unregister<T>();
}
DispatcherHelper.RunAsync(() =>
{
MessageBox.Show("Do GC now");
GC.Collect();
}, DispatcherPriority.ApplicationIdle);
});
}
(使用调度和优先级是一个测试)
如果我称之为有时我的记忆被正确释放,但并非总是如此。
在每一种情况下,如果我从例如快捷方式强制GC.Collect,我的记忆是正确管理。
在我的情况下释放内存的好方法是什么?
谢谢!
编辑:我的坏,它正常工作与代码(在我QuitCurrentContainerViewModel方法我使用这个检查:
if (!SimpleIoc.Default.ContainsCreated<T>())
但我需要这样的:
if (SimpleIoc.Default.ContainsCreated<T>())
这样,它似乎工作正常
感谢您的回复。我已经试图实现Idisposable没有成功。它认为dispose方法未被调用,因为视图在刷新之前“阻止”实例。 关于内存消耗,我使用私有字节的进程资源管理器性能视图。 – Tchoupi