AccessingPropertiesinOtherViewModelsinMVVMLight内容控件。我目前在ViewModel之间交换数据的方式是在主ViewModel中引用每个ViewModel,在每个UserControl中引用一个主ViewModel。但是我不知道这是否是正确的方法,因为我有一个ViewModelLocator并且我希望这个类有一些功能来支持这样的事情。谁能告诉我我现在是否正在这样做,或者MVVMLight中是否有更好的方法?编辑:当我在寻找不同的东西时,我发现了这个,这会是一个更好的解决方案吗?私人ViewModelLocator定位器=newViewModelLocator();然后使用定位器属性来引用每个ViewModel?EDIT2:显然我认为行得通的东西不是,起初我只在主ViewModel中有引用,它起作用了,但是当我在UserControls中尝试这个时,它使我的应用程序崩溃。我正在为第一次编辑尝试一个可能的解决方案。MainViewModel.cs(其他类似,仅指主ViewModel)publicclassMainViewModel:ViewModelBase{privateItemAddViewModelitemAddViewModel;私有ItemsViewModelitemsViewModel;//////初始化MainViewModel类的新实例。///publicMainViewModel(){ItemsList=Item.GetItemsList();itemAddViewModel=ServiceLocator.Current.GetInstance();itemsViewModel=ServiceLocator.Current.GetInstance();显示项目视图();}...privatevoidShowItemsView(){CurrentControl=itemsViewModel;}...你实际上可以使用ViewModelLocator。默认情况下使用控制容器的反转,因此即使您创建一个新的定位器实例,您也会从容器中获得相同的单例视图模型实例。定位器类:staticViewModelLocator(){ServiceLocator.SetLocatorProvider(()=>SimpleIoc.Default);SimpleIoc.Default.Register();SimpleIoc.Default.Register();SimpleIoc.Default.Register();}publicViewModel1ViewModel1{get{返回ServiceLocator.Current.GetInstance();}}publicViewModel2ViewModel2{get{返回ServiceLocator.Current.GetInstance();}}publicViewModel3ViewModel3{get{返回ServiceLocator.Current.GetInstance();然后从代码中访问它varvm1=(newViewModelLocator()).ViewModel1;您将获得viewmodel的唯一实例。来自xaml:资源(默认情况下在App.xaml中的Application.Resources中)和视图的DataContext(用户控件或窗口或其他)如果您只需要从主视图模型绑定属性,那么在内容控件中,只需使用以下语法:...Binding="{DataContext.mainvmpropertyname,ElementName=xxxx}"其中xxxx是附加到内容控件(或任何将主视图模型作为其DataContext的控件)的名称。或者,您可以使用相对绑定而不是元素名称。您可以通过从Apps资源获取定位器以编程方式访问ViewModel定位器的公共属性:MyViewModelvm=(App.Current.Resources["Locator"]asViewModelLocator).MyViewModel或者在ViewModelLocator类中创建另一个静态实例:public类ViewModelLocator{publicstaticViewModelLocatorInstance=newViewModelLocator();staticViewModelLocator(){...}publicMainViewModelMain{...}}类似线程以上是C#学习教程:MVVMLight中获取其他ViewModel中的属性共享如果对你有用还需要了解更多关于C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
