我看到人们建议在“当前”目标更改时使用 Messenger/EventAggregator 将参数传递给 ViewModel,但它对我的情况不起作用。
假设我有一个像这样的 ViewModel 类:
class CustomerViewModel
{
CustomerViewModel(int customerId) {}
}
和:
- 我在应用程序外壳中同时有相同类型的 View 。
- 对于每个 View ,都有一个唯一的 CustomerViewModel 实例。每个 CustomerViewModel 实例可以有不同的 customerId。 (类似于 Visual Studio IDE,打开多个文档 同时)
我不想在我的 View 类中编写类似“this.DataContext = new CustomerViewModel(id)”的代码。处理这种情况的 MVVM 方法是什么?
谢谢。
最佳答案
有几种方法可以处理这种情况,首先 - 确定您是否使用 View first or View Model first方法。
使用 EventAggregator 是一个有效的选项。
另一种选择是让您的 ViewModel 实现一个接口(interface),然后使用一些 IoC/DI例如MEF或 Unity 获取 ViewModel 的实例。使用此方法,您可以定义一个您知道 ViewModel 必须实现的 Initalize(int Id)
函数。
您不需要 View 知道 CustomerViewModel 类,只需要接口(interface)。
我应该指出,如果您使用某种DI,您始终可以将该参数注入(inject)到 ViewModel。 Unity 中的 IIRC 比在 MEF 中更容易完成(您只需注册该值,然后创建依赖于该类型的 ViewModel)。
关于c# - 如何在 WPF 应用程序中将参数传递给 ViewModel 的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13107064/