Accessing Properties in other ViewModels in MVVM Light

前端 未结 3 1137
说谎
说谎 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<ViewModel1>();
        SimpleIoc.Default.Register<ViewModel2>();
        SimpleIoc.Default.Register<ViewModel3>();
    }
    
    public ViewModel1 ViewModel1
    {
        get
        {
            return ServiceLocator.Current.GetInstance<ViewModel1>();
        }
    }
    
    public ViewModel2 ViewModel2
    {
        get
        {
            return ServiceLocator.Current.GetInstance<ViewModel2>();
        }
    }
    
    public ViewModel3 ViewModel3
    {
        get
        {
            return ServiceLocator.Current.GetInstance<ViewModel3>();
        }
    }
    

    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)

    <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
    

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

    <UserControl
        ... 
        DataContext="{Binding ViewModel1, Source={StaticResource Locator}}"
        ...    >
    
    0 讨论(0)
  • 2020-12-14 13:35

    You could access the public properties of the ViewModel Locator programatically by getting the Locator from the Apps resources:

    MyViewModel vm = (App.Current.Resources["Locator"] as ViewModelLocator).MyViewModel
    

    or by creating another static instance in the ViewModelLocator class:

    public class ViewModelLocator
    {
         public static ViewModelLocator Instance = new ViewModelLocator();
    
         static ViewModelLocator(){ ... }
    
         public MainViewModel Main
         {
         ...
         }
    }
    

    Similar Thread

    0 讨论(0)
  • 2020-12-14 13:38

    If all you need is to bind a property from the main viewmodel, while inside the content control, just use this syntax:

       ... Binding="{DataContext.mainvmpropertyname, ElementName=xxxx}"
    

    where xxxx is the Name attached to the content control (or any control that has the main viewmodel as its DataContext). Alternatively, you can use relative binding instead of element name.

    0 讨论(0)
提交回复
热议问题