Accessing Properties in other ViewModels in MVVM Light

前端 未结 3 1148
说谎
说谎 2020-12-14 12:51

I have a main ViewModel containing a List of items which I\'m using in a certain amount of UserControls, which are displayed in a ContentCont

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 13:19

    You can actually use the ViewModelLocator. Defaultly is uses the Inversion of Control Container, so even if you create a new instance of the Locator, you will get the same instance of singleton viewmodels from the container.

    The Locator class:

    static ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
        SimpleIoc.Default.Register();
        SimpleIoc.Default.Register();
        SimpleIoc.Default.Register();
    }
    
    public ViewModel1 ViewModel1
    {
        get
        {
            return ServiceLocator.Current.GetInstance();
        }
    }
    
    public ViewModel2 ViewModel2
    {
        get
        {
            return ServiceLocator.Current.GetInstance();
        }
    }
    
    public ViewModel3 ViewModel3
    {
        get
        {
            return ServiceLocator.Current.GetInstance();
        }
    }
    

    then from code you can access it as

    var vm1 = (new ViewModelLocator ()).ViewModel1;
    

    you get the one and only instance of viewmodel.

    from xaml: Resources (defaultly is in Application.Resources in App.xaml)

    
    

    and DataContext for views (either user controls or windows or whatever)

    
    

提交回复
热议问题