Hello stack overflow community, I'm new to MVVM and have worked on a couple of tutorials to get some of the basics working (bindings, RelayCommand etc..). A single window Application works so far pretty good, but now I need to add a Login and one or two other "views". I was not expecting this to be that painful.... :D
After working on a tutorial from (Github), I could figure out, if I place a button/command from the MainWindow.xaml for example to /view/Home.xaml the command still fires, the CurrentView also updates but the MainWindow doesn't update/show? So.... I'm very confused on what is going on, hopefully someone has a logical explanation.
After looking into a couple more examples on stack overflow, I was reading about MVVM light and messaging, is this the way to make things work? If so, could someone please show a simple example. not sure if a simple example exists..
Thank you very much, Anything is helpful
Alex
PS: I have updated my Navigation Test Repository github.com that shows exactly the issue. Hope there is an easy solution to this :D
UPDATE:
I have updated my code and came to the conclusion that I need to use either MVVM-light messaging or Prism Event Aggregator.
I decided to give Prism Event Aggregator a shot and have "tried" to implement the Interface and added the aggregator inside of my constructor in both view models, but now my whole solution doesn't work anymore. What am I doing wrong here?
NavigationViewModel.cs
public class NavigationViewModel : ViewModelBase
{
private IEventAggregator _eventAggregator;
public NavigationViewModel(IEventAggregator eventAggregator)
{
LoginCommand = new RelayCommand(Login);
PwResetCommand = new RelayCommand(PwReset);
LogoutCommand = new RelayCommand(Logout);
// Startup Page
CurrentView = new LoginViewModel();
//Prism Event Aggregator
_eventAggregator = eventAggregator;
eventAggregator
.GetEvent<MyEvent>()
.Publish(true);
}
public class MyEvent : PubSubEvent<bool>
{
}
WorkOrderViewModel.cs
public class WorkOrderViewModel : ViewModelBase
{
private IEventAggregator _eventAggregator;
public WorkOrderViewModel(IEventAggregator eventAggregator)
{
// Prism Event Aggregator
_eventAggregator = eventAggregator;
eventAggregator
.GetEvent<NavigationViewModel.MyEvent>()
.Subscribe(OnIsSavedEvent);
}
public void OnIsSavedEvent(bool isSaved)
{
bool IsModified = !isSaved;
}
}
NavigationView.xaml.cs:
public partial class NavigationView : UserControl
{
public NavigationView()
{
InitializeComponent(); // <-- System.NullReferenceException: 'Object reference not set to an instance of an object.'
}
}
I solved this by implementing MS Toolkit Messages, it was way simpler as I thought it would be.