I’m developing a WPF application with MVVM design pattern which makes use of the MVVM Light Toolkit. Currently I have a scenario like this.
I’m binding an Items Control to an Organization collection.
Here Employee itself is a user control which is reused in Existing and New Employee data.
User can update existing employee’s details (i.e. List) on every control's Lost Focus event. When it comes to adding a new employee, I handled the situation using user control Lost Focus Event. So on user control lost focus event using MVVM Light Toolkit EventToCommand, I’m passing EventArgs to View Model and then finding the Original Source from EventArgs(or traverse through the visual tree) to identify whether it’s to be inserted or not by checking whether the focus is within same user control using IsKeyBoardFocusWithin property.
Is this is the right implementation on MVVM pattern?
Also by doing the above approach I have to:
Traverse through the visual tree or to get the Original Source from EventArgs I have to make reference to System.Windows.Controls.
when it comes to unit testing, it would be more difficult to mock the EventArgs.
So is there any better MVVM approach to handle this scenario…
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
AddNewEmployeeBehavior
RelayCommand<Employee> AddNewEmployeeCommand;
to your VM.RelayCommand<Employee>
in AddNewEmployeeBehavior
AddNewEmployeeCommand
AddNewEmployeeBehavior
do what you were doing in the VM to check if a new item needs to be added to the List<Employee>
Employee
object.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With