How do you access the MainViewModel in ViewModelLocator from code behind?

最后都变了- 提交于 2019-12-03 09:16:42

If you created the ViewModelLocator as in the template you have static references to the ViewModels. The mvvmlocatorproperty-snippet creates ViewModel-properties like this. This means that you could just instantiate a new ViewModelLocator to locate the ViewModels in your code behind button click. It will always be the same viewmodels independent of the different instances of the ViewModelLocator

In MVVM-Light the ViewModelLocator is provided as an application resource. Therefore you can still directly access it, but the syntax is different. If you look at your App.xaml you should see this piece of code somewhere.

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

From anywhere in your application you can access the App's resources and therefore also the MainViewModel with this piece of code:

(App.Current.Resources["Locator"] as ViewModelLocator).Main

This works for any application resource.

To access the MainViewModel from your code you can add this property to your class:

public ViewModel.MainViewModel myContext { get { return (DataContext as ViewModel.MainViewModel); } }

Then you can just use myContext.[whatever]

You can just use ViewModelLocator.MainViewModelStatic. Default template for MVVMLight have a static property for each your viewmodel.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!