如何清除 MVVM Light xamarin 中 ViewModel 的数据?

How to clear data of ViewModel in MVVM Light xamrin?

I am working on Xamrin Form right now. I have problem with clear data of ViewModel.

当我注销并用不同的用户登录时,它会显示以前用户的数据,因为UserProfileViewModel的值不清楚。

当用户注销时,我想从 UserProfileViewModel class 文件中清除用户数据。目前我在用户点击注销时手动执行此操作。我想要像 dispose 这样的任何默认方法来清除所有 class 成员。

我曾尝试使用 this.Dispose(); 继承 IDisposable 接口,但这也没有用。

我也试过使用默认构造函数如下但它抛出错误

`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) 

数据。它是手动的。我想在用户注销时清除数据。

View Model Logout Page

 [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 会为你做。

但是,如果您就此使用 Messages 或任何其他 Strong Reference,您 WILL必须取消订阅,否则你的视图模式将在内存中徘徊,永远不会超出范围

The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object.

对于 Xamarin,这实际上取决于您如何将 View 耦合到 Viewmodals 以确定您可能采用哪种方法来清理 viewmodals。

事实证明 MVVM Light ViewModelBase 实现了一个 ICleanup 接口,它有一个 overridable Cleanup 方法供您使用。

ViewModelBase.Cleanup Method

To cleanup additional resources, override this method, clean up and then call base.Cleanup().

public virtual void Cleanup()
{
    // clean up your subs and stuff here
    MessengerInstance.Unregister(this);
}

现在你刚刚离开哪里可以打电话 ViewModelBase.Cleanup

如果您在 DataContextChanged 事件

上获得对 DataContext(即 ViewModalBase)的引用,您可以在视图关闭时调用它

或者你可以连接一个 BaseView 来为你探测这个,或者你可以实现你自己的 NagigationService,它在 Pop 上调用 Cleanup。这确实取决于谁在创建您的视图和视图模型以及您如何耦合它们