Oli
Oli

Reputation: 3136

Persisting Data Between MVVM View Changes

I have an application which contains a hierarchy of View/Viewmodels.

ViewModelBase contains two ViewModels

private AViewModel _aViewModel = new AViewModel();
private BViewModel _bViewModel = new AViewModel();

My XAML binds a DataControl to

private ViewModelBase _currentView {get; set;}
    public ViewModelBase CurrentView
    {
        get
        {
            return _currentView;
        }
        set
        {
            _currentView = value;
            RaisePropertyChanged("CurrentView");
        }
    }

And decides which view to display based on DataTemplates

<DataTemplate DataType="{x:Type vm:AViewModel}">
    <vw:AView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:BViewModel}">
    <vw:BView />
</DataTemplate>

All this works fine but I'm not sure how to persist data between View changes. Say for example that AViewModel contains a string called "Test" and has a two way binding in AView. By changing view using CurrentView = _bviewmodel then my data won't persist when I change back to _aviewmodel - What's the best way to make sure any data stays between view changes as opposed to creating a new blank viewmodel each time. I have to get _currentView to _aViewModel and then back to _currentView

Upvotes: 1

Views: 1631

Answers (2)

Oli
Oli

Reputation: 3136

Should have posted my AView xaml - Inside it was

 <UserControl.DataContext>
    <vm:AViewModel></vm:AViewModel>
</UserControl.DataContext>

So it appears I was stupidly creating a new ViewModel inside the Xaml everytime I changed the view. Thanks to everyone for pointing me in the right direction. I deleted this from the Xaml and all is working fine now.

Upvotes: 1

Maurizio Reginelli
Maurizio Reginelli

Reputation: 3222

Data should be persistent. Make sure that you don't create new ViewModels every time you change the CurrentView.

Upvotes: 1

Related Questions