As you mentioned yourself traversing through the Visual Tree should be avoided in the ViewModel
So an alternative to this approach could be using a Behavior - Tutorial
- So let's assume you create a Behavior called
AddNewEmployeeBehavior
- Next add a
RelayCommand<Employee> AddNewEmployeeCommand;
to your VM.
- Create a DP of type
RelayCommand<Employee>
in AddNewEmployeeBehavior
- In the View bind the DP of the Behavior to
AddNewEmployeeCommand
- Now in
AddNewEmployeeBehavior
do what you were doing in the VM to check if a new item needs to be added to the List<Employee>
- When new item is required to be added to the List kept in the VM / Model, Invoke the DP Command in the Behavior passing in the new Employee details wrapped into an
Employee
object.
- In the VM, create your RelayCommand accordingly to append it's invoked-with argument to the
List<Employee>
Now with this approach, you do not have any EventToCommand
stuff in the View. You simply have a Behavior taking a Command as a DP and have it invoke the Command when required based on the View only conditions you have.
As for unit-testing, that's very simple now cos all you have is a RelayCommand which you can invoke when desired in your unit-test.
This will hold as a MVVM solution since you no longer have any View related logic in your VM and the Behavior handles it for the View.
VM -> ViewModel
DP -> Dependency Property