In my WPF MVVM project I have a few forms and a database that holds employee information. There is an employee view model, this has an employeeId
passed to it, using the employee model, the employee's details are read from the database. This also reads if the employee is a 'User' or 'Admin'.
The view model will then decide which view to the load. The user view or the admin view. There are lots of similarities between the 2 views which is why I'm using the same view model for both.
This is why for my project I decided to be consistent and have my view models open their views. However, researching online I can only see advice saying to instantiate the view, which will then create the view model in the view constructor.
Is my method the wrong way for MVVM - and how would I do this scenario the right way?
MainWindowViewModel:
public void OpenSelectedEmployee(object employee)
{
if (employee == null)
return;
StaffListModel model = (StaffListModel)employee;
EmployeeViewModel vm = new EmployeeViewModel(model.EmployeeId);
}
EmployeeViewModel:
private EmployeeModel employee;
private Window employeeWindow;
// Employee View Model Constructor
public EmployeeViewModel(int employeeId)
{
// Connect to DB and read data for employee class
if (LoadEmployee(employeeId))
{
if (employee.UserType == "User")
employeeWindow = new EmployeeUserDetailsView();
else // if Admin
employeeWindow = new EmployeeAdminDetailsView();
employeeWindow.DataContext = this;
employeeWindow.ShowDialog();
}
else
{
// Open error message
MessageBox.Show("Error loading employee occurred");
}
}
I have considered storing the user type in the main window view model, so that decides which view to open. But if for any reason the database fails to read the employee (LoadEmployee(employeeId)
), there's no point creating the view and I would like the error message box to show.
Edit:
Here is the LoadEmployee
method currently in EmployeeViewModel
. It is used in the constructor and by a binding button to refresh the form.
public bool LoadEmployee(int employeeId)
{
if (!DbConnector.OpenDB())
return false;
try
{
employee = EmployeeModel.FindById(employeeId);
Depots = DepotModel.FindAllShort();
Departments = EmployeeModel.FindAllDepartments();
TenureHistory = TenureHistoryModel.FindAllByEmployeeId(employeeId);
IdCards = IdCardModel.FindAllByEmployeeId(employeeId);
Qualifications = QualificationModel.FindAllByEmployeeId(employeeId);
TheoryBookings = TheoryBookingModel.FindAllByEmployeeId(employeeId);
MedicalRecords = MedicalRecordModel.FindAllByEmployeeId(employeeId);
EyesightChecks = EyesightCheckModel.FindAllByEmployeeId(employeeId);
}
catch
{
DbConnector.CloseDB();
return false;
}
DbConnector.CloseDB();
return true;
}
public void Refresh(object parameter)
{
if (!LoadEmployee(employee.EmployeeId))
MessageBox.Show("An error has occurred");
NotifyPropertyChanged(string.Empty);
}