如何通过IoC获得视图模型第一种方法的设计时视图?

时间:2013-11-20 15:16:26

标签: caliburn.micro

我有一个包含其他视图模型的MasterViewModel

public MasterViewModel()
{
    User = new UserViewModel();
    Search = new SearchViewModel();
}

当我在MasterView添加

<Window ...
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cal="http://www.caliburnproject.org"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:viewModels="clr-namespace:MyApp.ViewModels"
    d:DataContext="{d:DesignInstance viewModels:MasterViewModel, IsDesignTimeCreatable=True}"
    cal:Bind.AtDesignTime="True"
    mc:Ignorable="d"
>

<ContentControl x:Name="User" />
<ContentControl x:Name="Search" />

我可以在设计时看到内容控件。

现在,我想通过IoC添加视图模型,如

public MainViewModel(UserViewModel user, SearchViewModel search, IEventAggregator events)
{
    User = user;
    Search = search;
}

但现在设计时间视图不再起作用了。 d:DataContext..的蓝色波浪形说,“没有为此对象定义无参数构造函数”。

我怎样才能让它发挥作用?

2 个答案:

答案 0 :(得分:1)

嗯,IoC(控制反转)的原理是依赖性求解发生在运行时而不是编译时

据我所知,设计人员不支持创建具有依赖关系的视图模型实例并为自己解决它们。因此需要 empty 构造函数。

如果你坚持设计时支持,这将是我使用的“黑客”。

public ShellViewModel() : this(new UserViewModel(), new SearchViewModel())
{
}

public ShellViewModel(UserViewModel user, SearchViewModel search, IEventAggregator events)
{
    User = user;
    Search = search;
}

但是可以想象,如果UserViewModel获得依赖关系,那么在开发更大的应用程序时这会变得很难看。新的依赖关系也可能有依赖关系,等等......你看,你只是遇到了IoC应该解决的问题。

但我认为你的ContentControl仍然是空的并不是太糟糕。您通过创建子视图模型实现的是将实际代码分离。你为什么要再次在你的设计师中结合它?因为相应的视图通过这些ContentControl分离。

视图模型层次结构越大,内容控制层次结构越大,在我看来,这会不必要地增加设计器中显示的项目数量。

答案 1 :(得分:0)

在这种情况下,更好的解决方案是使用DesignData而不是DesignInstance。需要在Blend中创建数据,但如果您使用的是VS2012 / VS2013,则Blend附带VS. 有关教程,请参阅这些链接。

http://visitmix.com/labs/rosetta/eyesofblend/datatemplates/ http://msdn.microsoft.com/en-us/magazine/dn169081.aspx

您要做的是创建“来自班级的样本数据”。这会将数据插入到类的虚构实例中,以及在字符串中插入lorem ipsum文本,在列表中插入几个项目等。

它将保留那些讨厌的空构造函数,并且您不需要在该空构造函数中维护测试数据。