Hi,
I'm trying to learn MVVMLIGHT, and using a simple wpf application with the below scenario.
1. My Main page has a ListBox bound to PreCreated employees.
2. When I click a button on the main page (button bound to AddEmployeeCommand, i'd like to open the Second window, which will have text boxes for creating a new employee.
3. When I click Add employee button on the second window, I want it to return that newly created employee to MainWindow.
My purpose here is to understand how Main window activates second window, and second window executes a callback to return the newly created employee.
Note: I have seen Laurent's videos of Messaging and have the sample code, but just not able to create the simple example above. Wanna know where i'm going wrong.
Here's the code I have right now:
MainVewModel
public class MainViewModel : ViewModelBase
{
private readonly IEmployeeService _employeeService;
private ObservableCollection<Employee> _employees;
public MainViewModel(IEmployeeService employeeService)
{
_employeeService = employeeService;
_employeeService.GetEmployees((listOfEmployees, error) =>
{
if (error != null)
{
return;
}
else
{
_employees = new ObservableCollection<Employee>(listOfEmployees);
}
});
}
public ObservableCollection<Employee> Employees
{
get { return _employees; }
}
public RelayCommand AddEmployeeCommand
{
get
{
return new RelayCommand(() => {
Messenger.Default.Send(new NotificationMessageAction<Employee>("Add new employee", NewEmployeeAdded));
});
}
}
private void NewEmployeeAdded(Employee newEmployee)
{
_employees.Add(newEmployee);
RaisePropertyChanged("Employees");
}
}
SecondVewModel:
public class SecondViewModel : ViewModelBase
{
private NotificationMessageAction _newEmployee;
public SecondViewModel()
{
Messenger.Default.Register<NotificationMessageAction<Employee>>(this,
emp =>
{
var secondWidnow = new SecondWindow();
secondWidnow.Show();
});
}
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name == value)
return;
else
{
_name = value;
RaisePropertyChanged("Name");
}
}
}
private string _department;
public string Department
{
get { return _department; }
set
{
if (_department == value)
return;
else
{
_department = value;
RaisePropertyChanged("Department");
}
}
}
private string _email;
public string Email
{
get{return _email;}
set
{
if (_email == value)
return;
else
{
_email = value;
RaisePropertyChanged("Email");
}
}
}
public RelayCommand AddEmployeeCommand
{
get
{
return new RelayCommand(() =>
{
var employee = new Employee
{
Name = _name,
Department = _department,
Email = _email
};
_newEmployee.Execute(employee);
});
}
}
}
If anyone can point me in the right direction, it would be great.
I'll include the code with this question.
Note: Also, if someone can tell me what message would be the right one for this kind, that would be helpful. I tried to use NotificationMessageAction<employee> since I wanted main window to get back the newly created employee.