c# - MVVMLight ViewModeloLocator to create new ViewModel -


i have been following mvvmlight code project. have 3 xaml files mainwindow, view1, view2,

i have registered 3 viewmodels in viewmodellocator, data service used view1model

    public viewmodellocator()     {         servicelocator.setlocatorprovider(() => simpleioc.default);         simpleioc.default.register<iview1service, view1service>();         simpleioc.default.register<mainviewmodel>();         simpleioc.default.register<view1model>();         simpleioc.default.register<view2model>();     }      public mainviewmodel main     {                 {             return servicelocator.current.getinstance<mainviewmodel>(guid.newguid().tostring());         }     }     public view1model view1     {                 {             return servicelocator.current.getinstance<view1model >(guid.newguid().tostring());         }     }     public view1model view2     {                 {             return servicelocator.current.getinstance<view2model >(guid.newguid().tostring());         }     } 

the view1model requires iview1service constructor input,

   public view1model(iview1service view1service)     {         _view1_service = view1service;     } 

in app.xaml have registered them below

<application.resources>     <vm:viewmodellocator x:key="locator" d:isdatasource="true" />     <datatemplate datatype="{x:type vm:view1model}">           <views:view1 />     </datatemplate>     <datatemplate datatype="{x:type vm:view2model}">           <views:view2 />     </datatemplate> </application.resources> 

and of course view1 view2 xmal files under myproject.view namespace.

i trying initialize views in mainviewmodel, access viewmodel instances in mainviewmodel

    public mainviewmodel()     {         // add available pages         pageviewmodels.add(new view1model(new view1service()));  // <========how viewmodellocator ?         pageviewmodels.add(new view1model());          // set starting page         currentpageviewmodel = pageviewmodels[0];      } 

pageviewmodels.add(new view1model()); in line of code, hoping viewmodellocator instead of passing view1service object. locator registered in app.xaml not accessible here, best way work around problem?

i creating viewmodellocator private field in viewmodel

public class myviewmodel : viewmodelbase {     private viewmodellocator _locator;      public myviewmodel()     {         _locator = new viewmodellocator();     } } 

then can access viewmodels through viewmodellocator using: _locator.view1, _locator.view2, etc.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -