1

Visual Studio 2008 设计器似乎不喜欢引用 MVVM-Light ViewModelLocator 的 UserControl。我收到一条错误消息,例如:

无法创建“MyUserControl”类型的实例。

例如,如果 MyUserControl 使用 ViewModelLocator 建立其 DataContext,则以下 XAML 将导致此行为。

<Page x:Class="MyProject.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Views="clr-namespace:MyProject.Views"
>
    <Grid>
        <Views:MyUserControl/>
    </Grid>
</Page>

MyUserControl 非常简单:

<UserControl x:Class="MyProject.Views.MyUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         DataContext="{Binding MyNestedViewModel, Source={StaticResource Locator}}"
>
<Grid>
    <TextBlock>Hello</TextBlock>
</Grid>
</UserControl>

而“MyNestedViewModel”属性只是实例化了 MyNestedViewModel 类的一个实例,它的默认构造函数中绝对没有代码。

两个问题:

  1. 我正确使用 ViewModelLocator 吗?也就是说,它可以在嵌套视图中使用还是仅用于顶级视图?
  2. 这可能只是 Visual Studio 2008 设计器 Cider 中的另一个错误吗?

请注意,一切都在运行时完美运行。我只在设计时遇到问题。但我讨厌盲目编码 XAML。

4

1 回答 1

0

我在 VS 2010 中遇到了同样的情况。我刚刚发现的部分解决方法......

在您的用户控件中,更改DataContextd:DataContext

<UserControl x:Class="MyProject.Views.MyUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         d:DataContext="{Binding MyNestedViewModel, Source={StaticResource Locator}}"
>
<Grid>
    <TextBlock>Hello</TextBlock>
</Grid>
</UserControl>

不幸的是,我无法让它在 UserControl YET 中显示数据,只是 UserControl 本身。

于 2010-11-03T17:36:06.157 回答