WPF MVVM ViewModel containing ViewModels not updating

629 Views Asked by At

I'm very new to WPF and MVVM, and it's been causing me a lot of headaches. Due to issues with navigation, I decided to just have all my content visible at once. I thought I would create a new ViewModel (MainViewModel) to contain my two other ViewModels (StudentViewModel and AddStudentsViewModel).

MainViewModel contains something like this:

private StudentViewModel _studentVM;
private AddStudentsViewModel _addStudentsVM;

public StudentViewModel StudentVM
{
    get { return _studentVM; }
    set
    {
        if (_studentVM != value)
        {
            _studentVM = value;
            NotifyPropertyChanged("StudentVM");
        }
    }
}

(public AddStudentsViewModel AddStudentsVM exists as well, I'm just trying to keep this short)

I have successfully bound StudentVM and AddStudentsVM to my main View, as I can programmatically set values during the initialization phase and when debugging, I can see my button clicks are being redirected to the correct methods. It even seems like I am successfully adding students to objects, however my main View isn't reflecting these changes.

Am I missing something in MainViewModel? Or is it not possible for a ViewModel to see the changes in any other ViewModels inside it?

2

There are 2 best solutions below

0
On

If your view is bound to some property inside StudentViewModel through nested navigation into the property StudentVM like StudentVM.Property, then to reflect changes on StudentVM.Property unto your view would require that you notify the view that StudentVM (not StudentVM.Property) has changed.

So it depends on how you defined your binding and on which property you're raising the PropertyChanged event.

2
On

A viewmodel which contains two other viewmodels. Just think about it for a second. It's not a good idea.

Anyway, you have to implement INotifyPropertyChanged in your containing viewmodels as well. Not only in the containing MainViewModel.

Maybe that is the fault?