MVVM-Light ViewModelLocator可以在嵌套ViewModel中使用吗? [英] Can the MVVM-Light ViewModelLocator be used in nested ViewModels?
问题描述
Visual Studio 2008设计器似乎不喜欢引用MVVM-Light ViewModelLocator的UserControl.我收到如下错误消息:
The Visual Studio 2008 Designer doesn't seem to like UserControls that reference the MVVM-Light ViewModelLocator. I get an error message like:
无法创建类型为"MyUserControl"的实例.
Could not create an instance of type 'MyUserControl'.
例如,如果MyUserControl使用ViewModelLocator建立其DataContext,则以下XAML会导致此行为.
For example, the following XAML will cause this behavior if MyUserControl uses the ViewModelLocator to establish its DataContext.
<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非常简单:
MyUserControl is extremely simple:
<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类的实例,该类的默认构造函数中绝对没有代码.
And the "MyNestedViewModel" property simply instantiates an instance of the MyNestedViewModel class, which has absolutely no code in its default constructor.
两个问题:
- 我是否正确使用ViewModelLocator?也就是说,它可以在嵌套视图中使用还是仅用于顶级视图?
- 这可能只是Visual Studio 2008设计器Cider中的另一个错误吗?
请注意,一切都在运行时完美运行.我只在设计时遇到问题.但是我讨厌对XAML进行盲目编码.
Note that everything works perfectly at runtime. I only have problems at design time. But I hate coding XAML blind.
推荐答案
我在VS 2010中遇到了同样的情况.我只是发现了部分解决方法...
I encounter the same situation in VS 2010. A partial workaround I JUST discovered...
在您的UserControl中,将DataContext
更改为d:DataContext
In your UserControl, change DataContext
to d: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本身中显示.
Unfortunately, I can't get it to display data in the UserControl YET, just the UserControl itself.
这篇关于MVVM-Light ViewModelLocator可以在嵌套ViewModel中使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!