Can the MVVM-Light ViewModelLocator be used in nested ViewModels?

别来无恙 提交于 2019-12-06 13:20:11

问题


The Visual Studio 2008 Designer doesn't seem to like UserControls that reference the MVVM-Light ViewModelLocator. I get an error message like:

Could not create an instance of type 'MyUserControl'.

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 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>

And the "MyNestedViewModel" property simply instantiates an instance of the MyNestedViewModel class, which has absolutely no code in its default constructor.

Two questions:

  1. Am I using the ViewModelLocator correctly? That is, can it be used in nested views or is it only meant for top-level Views?
  2. Could this just be another bug in Cider, the Visual Studio 2008 designer?

Note that everything works perfectly at runtime. I only have problems at design time. But I hate coding XAML blind.


回答1:


I encounter the same situation in VS 2010. A partial workaround I JUST discovered...

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>

Unfortunately, I can't get it to display data in the UserControl YET, just the UserControl itself.



来源:https://stackoverflow.com/questions/3010923/can-the-mvvm-light-viewmodellocator-be-used-in-nested-viewmodels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!