0

I am trying to create a WPF Model-View-ViewModel that has separate LoginWindow, RegistrationWindow and MainDashboardWindow.

I have already read Rachel Lim's solution on navigating with MVVM using ApplicationViewModel and ApplicationView that contains other views but I have trouble understanding something.

enter image description here

I was planning on using LoginViewModel and RegistrationViewmodel (none of them will inherit from BaseViewModel) by setting the DataContext of LoginWindow and RegistrationWindow and then after logging in to application start using a MainDashboardViewModel to switch between viewmodel's on MainDashboardWindow.

Is this the correct way to go? If this is not the correct way to go, how can I implement an application-wide viewmodel that can be switched between windows (only one window will be opened at a time)?

Milan
  • 65
  • 1
  • 11

1 Answers1

1

To implement MVVM properly, you need to understand what is View, Model and ViewModel.

View is the UI that WON'T HAVE ANY CODE. The DataContext in View is the ViewModel class, one View should be associated with one ViewModel. You should set the DataContext by XAML code.

Model is the class contains the data and some methods to process for that data. I highly recommend you using Repository Pattern when design Model for you program.

ViewModel is where you put the business method in it. All ViewModel must implement from BaseViewModel and DON'T KNOW ANYTHING ABOUT VIEW.

In your case, you need to create 3 different Views, 3 ViewModels for 3 Views.

Let's start with your Login windows. First you need to specify what ViewModel for Login windows by indicate it on Login view.

<Window x:Class="SampleApplication.LoginWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SampleApplication.ViewModels"
    Title="Login" Height="350" Width="525">
<Window.DataContext>
   <local:LoginViewModel/>
</Window.DataContext>

You have 2 buttons in Login windows. one is Login and on is Register. Each button must be binded with an RelayCommand in ViewModel. By this way you can properly implement MVVM. To navigate between windows you must close you current windows and open a new one. To close windows, see this, to open windows, just create an object of your view and call ViewObject.Show();

Red Wei
  • 854
  • 6
  • 22