There is a problem with the way WPF handles property changes along with your way of notifying the change. WPF checks to see if your value is still the same; the EmployeeCollection is actually the same as the old one (it is still the same instance and it won't look inside the collection).
One solution is to change the implementation of EmployeeCollection
to this:
public class EmployeeCollection : IEnumerable, INotifyCollectionChanged
{
private ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
public EmployeeCollection()
{
employees.Add(new Employee(100, "Alice", 23, 300));
employees.Add(new Employee(100, "Bob", 22, 400));
employees.Add(new Employee(100, "Trude", 21, 200));
}
public IEnumerator GetEnumerator()
{
return employees.GetEnumerator();
}
public void AddNewEmployee() //For Test
{
employees.Add(new Employee(200, "Dave", 21, 2000));
}
public event NotifyCollectionChangedEventHandler CollectionChanged
{
add { employees.CollectionChanged += value; }
remove { employees.CollectionChanged -= value; }
}
}
This introduces the INotifyCollectionChanged
interface and removes the need to call vm.NotifyOnEmployeeCollectionChanged()
in the main window, since the ObservableCollection<T>
underlying the EmployeeCollection
will tell WPF that it has changed.
If you do not want to learn about these concepts for now, a quick work around would be to :
public void NotifyOnEmployeeCollectionChanged()
{
var current = this.employees;
this.employees = null;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Employees"));
this.employees = current;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Employees"));
}