8

我正在开发一个带有 MVVM 设计模式的 WPF 应用程序,它使用了 MVVM Light Toolkit。目前我有这样的场景。

在此处输入图像描述

我将项目控件绑定到组织集合。

  1. 由组织名称和列表组成的组织。
  2. 由项目名称、列表和新员工组成的项目
  3. 员工由员工姓名、联系电话和电子邮件组成

在此处输入图像描述

这里 Employee 本身是一个用户控件,在 Existing 和 New Employee 数据中被重用。

用户可以在每个控件的失去焦点事件上更新现有员工的详细信息(即列表)。在添加新员工时,我使用用户控件Lost Focus Event 来处理这种情况。因此,在使用 MVVM Light Toolkit EventToCommand的用户控制失去焦点事件上,我将 EventArgs 传递给 View Model,然后从EventArgs中找到原始源(或遍历可视化树)以通过检查是否插入来确定是否要插入焦点位于使用 IsKeyBoardFocusWithin 属性的同一用户控件中。

这是 MVVM 模式的正确实现吗?

同样通过上述方法,我必须:

  1. 遍历可视化树或从 EventArgs 中获取原始源,我必须参考 System.Windows.Controls。

  2. 当涉及到单元测试时,模拟 EventArgs 会更加困难。

那么有没有更好的 MVVM 方法来处理这种情况……</p>

4

1 回答 1

3

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

于 2013-05-08T14:46:07.097 回答