1

I've recently read few articles about using IoC in MVVM application. This great answer for example. And I started thinking, what If I have single View and four ViewModels. I don't know which one should be attached to the View's DataContext at the design time. I will know that during runtime.

Like, in that answer I have locator:

class IocConfiguration : NinjectModule
{
    public override void Load()
    {
        Bind<IStorage>().To<Storage>().InSingletonScope();

        Bind<UserControlViewModel>().ToSelf().InTransientScope().WithConstructorArguments( ... ).Named("UserControlViewModelA");
        Bind<UserControlViewModel>().ToSelf().InTransientScope().WithConstructorArguments( ... ).Named("UserControlViewModelB");
        Bind<UserControlViewModel>().ToSelf().InTransientScope().WithConstructorArguments( ... ).Named("UserControlViewModelC");
        Bind<UserControlViewModel>().ToSelf().InTransientScope().WithConstructorArguments( ... ).Named("UserControlViewModelD");

    }
}

class ViewModelLocator
{
    public UserControlViewModel UserControlViewModelA
    {
        get { return IocKernel.Get<UserControlViewModel>("UserControlViewModelA"); }
    }

    public UserControlViewModel UserControlViewModelB
    {
        get { return IocKernel.Get<UserControlViewModel>("UserControlViewModelB"); }
    }

    public UserControlViewModel UserControlViewModelC
    {
        get { return IocKernel.Get<UserControlViewModel>("UserControlViewModelC"); }
    }

    public UserControlViewModel UserControlViewModelD
    {
        get { return IocKernel.Get<UserControlViewModel>("UserControlViewModelD"); }
    }        
}

My question is. How should I handle it in my View? which is:

<UserControl 
    ...
    DataContext="{Binding UserControlViewModelA, Source={StaticResource ViewModelLocator}}">

    <Grid>
    </Grid>
</UserControl>

What I mean is, I am struggling with assigning different ViewModel at runtime. Design time is not a problem. The problem is what approach should I take to set particular ViewModel to this view at runtime and keep best programming practices alive

Community
  • 1
  • 1
robertwojnar
  • 119
  • 2
  • 10

0 Answers0