Search code examples
xamlmvvmwin-universal-appmvvm-lightviewmodellocator

UWP + MvvmLight - ViewModelLocator defined as App.xaml resource is returning Access Denied error in Design Mode


I'm building UWP app with MVVMLight and I have problem with my ViewModelLocator in Design Mode.

I created ViewModelLocator:

public class ViewModelLocator
{
  public MainPageViewModel Main =>ServiceLocator.Current.GetInstance<MainPageViewModel>();


  static ViewModelLocator()
  {
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<MainPageViewModel>();

    if (ViewModelBase.IsInDesignModeStatic)
    {
      SimpleIoc.Default.Register<IMainPageDataService, DesignMainPageDataService>();
    }
    else
    {         
      SimpleIoc.Default.Register<IMainPageDataService, MainPageDataService>();              
    }
  }
}

And then I declared it as App resource:

<Application.Resources>
  <ResourceDictionary>
    <viewModels:ViewModelLocator x:Key="Locator"></viewModels:ViewModelLocator>  
  </ResourceDictionary>
</Application.Resources>

It should work now and I should have possibility to define MainPageViewModel as MainPage DataContext but Intellisense is underlining

<viewModels:ViewModelLocator x:Key="Locator"></viewModels:ViewModelLocator>

with error

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

I noticed that when I'm not using ViewModelBase.IsInDesignModeStatic property it works properly and I can see design data at MainPage. Something like this works:

public class ViewModelLocator
{
  public MainPageViewModel Main =>ServiceLocator.Current.GetInstance<MainPageViewModel>();


  static ViewModelLocator()
  {
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<MainPageViewModel>();

    SimpleIoc.Default.Register<IMainPageDataService, DesignMainPageDataService>();
  }
}

Have you any ideas to resolve this weird problem?


Solution

  • Well... it was something wrong with my environment. I checked it on another machine and it works flawless.