Kefka
Kefka

Reputation: 89

WPF: navigating between user controls resets viewmodel

I have an application where I am using usercontrols as "pages" of the application. I have a currentpage binding in ApplicationViewModel on my MainWindow, and I navigate between pages by changing the binding of currentpage with commands attached to a side menu control. I am using the MVVM pattern and all of my ViewModels derive from a BaseViewModel class.

The navigation works, but when I input text into a text box, then navigate away and then back, the user-input text is reset to it's default binding.

I've already tried updating the source trigger and setting the mode to TwoWay. My "page" has a viewmodel which it is bound to, and otherwise works.

On my page, in the parent grid all controls are in:

DataContext="{x:Static core:MyPageViewModel.Instance}">

And the control:

<TextBox Text="{Binding TextBoxTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

And in my viewmodel:

public static MyPageViewModel Instance => new MyPageViewModel(); public string TextBoxTest { get; set; } = "Change Me!";

I would like the value I enter to remain when I navigate away, and then return, to the page. I assume it's because when I navigate away from my usercontrol I'm unloading it, and when I navigate back I'm getting a new instance of the viewmodel. I just don't know how to keep a single one that remains in memory.

Upvotes: 0

Views: 816

Answers (2)

Kefka
Kefka

Reputation: 89

Guido C. was exactly correct. I changed my viewmodel instance from the way I had it in my question to this:

public static MyPageViewModel Instance { get; } = new MyPageViewModel();

And it worked.

Upvotes: 0

Guido Cardinali
Guido Cardinali

Reputation: 376

You should post more code, it's not clear from the pieces.

I can try to guess anyway the problem is here:

public static MyPageViewModel Instance => new MyPageViewModel();

This generates a new ViewModel every time it is accessed by your view, because it is the equivalent of writing:

public static MyPageViewModel Instance { get { return new MyPageViewModel(); } }

instead, you should write something like

public static MyPageViewModel Instance { get; } = new MyPageViewModel();

This way, the first time it is accessed, it returns the default value (new MyPageViewModel()), and now that static variable will always point to the same view model, instead of creating a new one.

Upvotes: 1

Related Questions