使用Xamarin.Forms弹出页面后如何处置ViewModel? [英] How to Dispose a ViewModel after Popping a page with Xamarin.Forms?

查看:328
本文介绍了使用Xamarin.Forms弹出页面后如何处置ViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是在不再需要ViewModel时取消订阅事件.我尝试实现IDisposable,但没有人调用Dispose(),而不是Xamarin.Forms或Prism.Forms.

What I would like to do is unsubscribe from events at the moment the ViewModel is no longer needed. I tried implementing IDisposable but nobody calls Dispose(), not Xamarin.Forms nor Prism.Forms.

我们有一个使用Xamarin.Forms创建的应用程序.我们使用Prism.Forms进行MVVM.导航到新页面(堆叠时)时,Prism.Forms将ViewModel连接到页面.向后导航(从堆栈弹出)时,ViewModel会在一段时间后变为GarbageCollected.

We have an app created with Xamarin.Forms. We use Prism.Forms to do MVVM. When navigating to a new page (push on stack) Prism.Forms wires the ViewModel to the Page. When navigating back (pop from stack) the ViewModel gets GarbageCollected after a while.

但是问题是,在某个时间点上,我们有几个相同类型的ViewModel,它们都订阅了未绑定到View的事件.当事件触发时,所有这些ViewModel都会开始执行其操作.因此,我正在寻找一种不再需要订阅的方式来取消订阅.

The problem is however that at a point in time we have a couple of the same type of ViewModels with subscriptions to events that are not bound to a View. When the events fire all these ViewModels start doing their thing. So I am looking for a way to unsubscribe at the moment the subscription is no longer needed.

有人可以解决吗?

推荐答案

如果要确保ViewModel不再存在,则可以确保在View的OnDisappearing()事件中调用Dispose().内存比视图.

You can make sure the Dispose() is called in the OnDisappearing() event of the View, if you want to ensure that ViewModel is not present anymore in the memory than the view.

最好只关心事件的订阅和取消订阅,然后在OnAppearing()OnDisappearing()中进行.在这种情况下,一旦视图不可见,您将确保在视图模型上不存在任何事件处理程序.

It is better if you care only about subscribe and unsubscribe of events, then to do it in the OnAppearing() and OnDisappearing(). In that case you will be sure of no event handlers been present on the viewmodel once view is not visible.

这篇关于使用Xamarin.Forms弹出页面后如何处置ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆