简体   繁体   English

在MVVM Light中使用ViewModel?

[英]Working with the ViewModels in MVVM Light?

Basically I had created my application entirely using code behind and now I'm migrating over to MVVM. 基本上,我完全使用背后的代码创建了应用程序,现在我正在迁移到MVVM。 One of the challenges that I'm facing is how to deal with ViewModels that are being persisted in memory. 我面临的挑战之一是如何处理持久化在内存中的ViewModel。

For example in the first version of my app I knew once the user hit the back button on a certain page that the view would be discarded and that everything would be cleared, but when I started using the ViewModel and navigated to the page it was using the ViewModel that was created the previous time I navigated to the page (In other words the constructor wasn't called). 例如,在我的应用程序的第一个版本中,我知道一旦用户单击某个页面上的“后退”按钮,该视图将被丢弃并且所有内容将被清除,但是当我开始使用ViewModel并导航到该页面时我上次浏览到页面时创建的ViewModel(换句话说,没有调用构造函数)。

Now is this the way it's supposed to work? 现在这是应该工作的方式吗? I would prefer that I recreate the ViewModel everytime I navigate forward and discard it everytime I hit back. 我希望每次导航时都重新创建ViewModel,而每次回击时都将其丢弃。 But like I said this is new to me. 但是就像我说的那样,这对我来说是新的。 Am I supposed to use the same viewmodel and somehow refresh the values so it doesn't show old data? 我是否应该使用相同的视图模型并以某种方式刷新值,以使其不显示旧数据?

Here's how I clear the view model when the user leaves the page (this code is in the page's xaml.cs) file: 这是当用户离开页面(此代码在页面的xaml.cs中)文件时清除视图模型的方式:

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.Back)
                ViewModelLocator.ClearDetailsViewModel();

            base.OnNavigatingFrom(e);
        }

the implementation of ClearDetailsViewModel is like ClearDetailsViewModel的实现就像

if (_detailsViewModelStatic == null) return;
 _detailsViewModelStatic.Cleanup();
_detailsViewModelStatic = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM