我正在我们的WPF应用程序中使用MVVM模式,以便可以进行全面的单元测试。 MVVM模式本身运作良好,但我在努力使该模式适应一种方式,以便我可以使用WPF的设计时数据支持。
由于我正在使用Prism,因此ViewModel实例通常会被注入到视图的构造函数中,如下所示:
public MyView(MyViewModel viewModel)
{
DataContext = viewModel;
}
然后,ViewModel所需的依赖项将被注入到构造函数中,如下所示
public class MyViewModel
{
public MyViewModel(IFoo foo, IBar bar)
{
// ...
}
// Gets and sets the model represented in the view
public MyModel { get; set; }
// Read-only properties that the view data binds to
public ICollectionView Rows { get; }
public string Title { get; }
// Read-write properties are databound to the UI and are used to control logic
public string Filter { get; set; }
}
总的来说,这个方法运行得非常好,只是在设计数据方面有点问题——我想避免把设计数据专用的类编译到我的发布程序集中,因此我选择使用 {d:DesignData}
方法而不是 {d:DesignInstance}
方法,但是为了让它正确地工作,我的 ViewModel 现在需要一个无参数的构造函数。另外,我还经常需要将其他属性更改为具有 setter 或可修改集合以便能够在 XAML 中设置这些属性。
public class MyViewModel
{
public MyViewModel()
{
}
public MyViewModel(IFoo foo, IBar bar)
{
// ...
}
// Gets and sets the model represented in the view
public MyModel { get; set; }
// My read-only properties are no longer read-only
public ObservableCollection<Something> Rows { get; }
public string Title { get; set; }
public string Filter { get; set; }
}
这让我感到担忧:
- 我有一个无参数构造函数,从未想过要调用它,也没有经过单元测试。
- 有一些属性的setters只应该由ViewModel自己调用。
- 现在我的ViewModel中混杂着应该由视图修改的属性和不应该修改的属性 - 这使得一眼看去很难判断哪段代码负责维护任何给定的属性。
- 在设计时设置某些属性(例如为了在
Filter
文本上查看样式)实际上可能会触发ViewModel逻辑!(因此我的ViewModel还需要容忍在设计时缺少其他依赖项)。
在WPF MVVM应用程序中,有没有更好的方法以一种不会损害我的ViewModel的方式获得设计时数据?
或者,我应该以一种不同的方式构建我的ViewModel,以便它具有更简单的属性,并将逻辑分离到其他地方。