Search code examples
wpfvb.netmvvmviewmodel

Variable values become null after clicking on second window opened from first window's view model


The software I am working on has a Mainwindow in which there are several buttons that open new windows. Each of these should have a ViewModel.

In the MainWindowViewModel the software creates some data, eg ProList and summariesData. One of the buttons in the main window that opens a new window is "Show Bars" button. In the MainWindowViewModel, I have connected Show bars button with ICommand to a method that instantiates the new window. I use code-behind Show Bar buttons to open the new window.

Dim wndSummariesObject = New WndSummaries
wndSummariesObject.Show()

In the same method, I instantiate the ShowbarsViewModel to pass the data it needs to work with.

WndSummariesViewModelObject = new WndSummariesViewModel(_ProfileList, 
    SummariesWndData) With {
        .ProfileList = ProList,
        .SummariesWndData = SummariesData
    }

It shows that the constructor transfers the data into the ShowBarsViewModel, but the problem is when I click on one of the buttons in the Show bar button to operate its task, I lose all the variables' values that were instantiated and transferred before from the MainWindowViewModel!

Where am I making the mistake?

------- Update

It has the same behavior(Making null) when I want to send the instance of the first ViewModel as a parameter of the constructor of the second ViewModel.


Solution

  • The problem was that in Xaml I was setting an instance of the ViewModels. Even though I was setting the parameters in the constructor, but the second ViewModel was using the one that was created in the Xaml mistakenly.

    <Window.Resources>
         <ViewModels:WndSummariesViewModel x:Key="WndSummariesVM"/>
         <viewModels:ProViewModel x:Key="ProViewModel" />
    </Window.Resources>