【发布时间】:2016-04-29 02:07:28
【问题描述】:
我目前正在使用 ContentControl 通过设置 VM 并使用这样的默认数据模板来显示我的视图:
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:MyViewViewModel}">
<views:MyView />
</DataTemplate>
</UserControl.Resources>
<ContentControl Content="{Binding ContainerContent}"/>
这是我的容器内容:
public ViewModelBase ContainerContent
{
get
{
return _containerContent;
}
set
{
if (_containerContent != null)
_containerContent.Cleanup();
_containerContent = value;
RaisePropertyChanged("ContainerContent");
}
}
我目前使用 SimpleIoc 通过 serviceLocator 加载 ViewModel:
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>())
这样看来效果不错。
【问题讨论】:
标签: c# wpf mvvm mvvm-light ioc-container