棱镜地区不可处置意见或的ViewModels [英] Prism Regions Not Disposing Views or ViewModels
问题描述
我认为棱镜地区会自动检测并调用的Dispose
的实施的IDisposable
接口的任何意见或视图模型。事实证明我错了。
I assumed that Prism Regions would automatically detect and call Dispose
any views or view models that implemented the IDisposable
interface. Turns out I was wrong.
然后我考虑实施 IActiveAware
,所以我可以处理我自己我的看法/的ViewModels,但似乎相当的hackish 。我宁愿把它自动完成的。
I then considered implementing IActiveAware
so I could dispose my views/viewmodels on my own, but that seems rather hackish. I'd rather have it done automatically.
我如何配置棱镜地区自动配置我的看法和视图模型实现的IDisposable
?
How can I configure Prism Regions to automatically dispose my views and view models that implement IDisposable
?
推荐答案
搜索无远弗届的互联网上,并没有找到任何真正的解决方案后,我开发了我自己自 RegionBehavior
,这竟然非常漂亮的工作。
After searching far and wide on the internet, and not finding any real solution, I developed my own custom RegionBehavior
, which turned out to work very nicely.
行为监听区域的观点收集的任何变化,并能在任何有删除,它会检查并要求的Dispose
对视图和/或视图模型,只有当他们执行<$ C $ 。C>的IDisposable
The behavior listens to the region's view collection for any changes, and when any are removed, it checks for and calls Dispose
on the view and/or view model, only if they implement IDisposable
.
class DisposeClosedViewsBehavior : RegionBehavior
{
protected override void OnAttach()
{
Region.Views.CollectionChanged += Views_CollectionChanged;
}
private void Views_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Remove) return;
foreach (var removedView in e.OldItems)
{
IDisposable disposableView = removedView as IDisposable;
IDisposable disposableViewModel;
var iviewView = removedView as IView;
if (iviewView != null)
{
disposableViewModel = iviewView.DataContext as IDisposable;
}
else
{
var frameworkElementView = removedView as FrameworkElement;
disposableViewModel = frameworkElementView?.DataContext as IDisposable;
}
disposableView?.Dispose();
disposableViewModel?.Dispose();
}
}
}
最后一步是为了堵塞这种行为变成棱镜通过重写引导程序 ConfigureDefaultRegionBehaviors
方法:
protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
{
var factory = base.ConfigureDefaultRegionBehaviors();
factory.AddIfMissing(nameof(DisposeClosedViewsBehavior), typeof(DisposeClosedViewsBehavior));
return factory;
}
工程就像一个魅力!
Works like a charm!
这篇关于棱镜地区不可处置意见或的ViewModels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!