我现在正在使用Xamrin Form。我对ViewModel的清晰数据有疑问。
当我注销并用其他用户登录时,它会显示前一个用户的数据,因为的值UserProfileViewModel
不清楚。
用户注销时,我想从UserProfileViewModel类文件中清除用户数据。当前,当用户单击注销时,我会手动执行此操作。我想要像处置这样的默认方法来清除所有类成员。
我试图用继承IDisposable接口,this.Dispose();
但是那也没有用。
我也尝试过以下默认构造函数,但会引发以下错误
`System.TypeInitializationException`
在app.xaml.cs的这一行上: public static ViewModelLocator Locator => _locator ?? (_locator = new ViewModelLocator());
public UserProfileViewModel()
{
//initialize all class member
}
在给定的代码中,您可以看到在注销调用时,我调用了方法
`ClearProfileData` of `UserProfileViewModel`
which set default(clear)
数据。它是手动的。我要在用户注销时清除数据。
查看模型注销页面
[ImplementPropertyChanged]
public class LogoutViewModel : ViewModelBase
{
public LogoutViewModel(INavigationService nService, CurrentUserContext uContext, INotificationService inService)
{
//initialize all class member
private void Logout()
{
//call method of UserProfileViewModel
App.Locator.UserProfile.ClearProfileData();
//code for logout
}
}
}
User Profile View Model
[ImplementPropertyChanged]
public class UserProfileViewModel : ViewModelBase
{
public UserProfileViewModel(INavigationService nService, CurrentUserContext uContext, INotificationService inService)
{
//initialize all class member
}
//Is there any other way to clear the data rather manually?
public void ClearProfileData()
{
FirstName = LastName = UserName = string.Empty;
}
}
ViewModel Locator
public class ViewModelLocator
{
static ViewModelLocator()
{
MySol.Default.Register<UserProfileViewModel>();
}
public UserProfileViewModel UserProfile => ServiceLocator.Current.GetInstance<UserProfileViewModel>();
}
首先,无需清理这些原始数据类型,gc会为您完成。
但是,如果你使用的邮件或任何其他强参照为此事你WILL不得不取消从它们,否则你将viewmodal流连于记忆,绝不会去的范围之
当应用程序的代码可以到达该对象时,垃圾收集器无法收集该应用程序正在使用的对象。据说该应用程序对该对象有很强的引用。
使用Xamarin,实际上取决于您如何将View与Viewmodals耦合,以确定您可以采用哪种方法来清理Viewmodal。
事实证明,MVVM Light ViewModelBase
实现了ICleanup接口,该接口为您提供了可重写的Cleanup方法。
要清理其他资源,请重写此方法,清理然后调用base.Cleanup()。
public virtual void Cleanup()
{
// clean up your subs and stuff here
MessengerInstance.Unregister(this);
}
现在您只剩下在哪里调用ViewModelBase.Cleanup
如果您引用了事件上的DataContext
(Ie ViewModalBase
),则只需在视图关闭时调用它DataContextChanged
或者你也可以连线了BaseView
该铅垂线这个给你,或者你可以实现你自己的NagigationService
哪个电话Cleanup
上Pop
。它确实取决于谁在创建视图和视图模型以及如何耦合它们
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句