Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access one ViewModel's object in another ViewModel in WPF application using MVVM

Tags:

c#

mvvm

wpf

I am using mvvm pattern in WPF application and not using any database. I stuck in to problem where I have a view UploadView in which user uploads some excel file and its view model named as UploadViewModel in this I read uploaded files data and keeps it in some datatable object which is UploadvViewModals class's object and it is working fine but my problem is that now I have to display uploaded data(datatable object) it on some another view in a some ItemsControl having different Viewmodal. Being a newbie in WPF and windows.I dont know how to proceed. What are the possible ways to do this?

like image 907
SST Avatar asked Sep 17 '12 13:09

SST


People also ask

How do I transfer data from one ViewModel to another ViewModel?

To pass data from the Main View/Main ViewModel to the Detail ViewModel, assign the data to the ViewModelExtensions. Parameter attached property on the Detail View instance.

Can ViewModel contain other ViewModels?

It is perfectly right to have ViewModel contains ViewModel. Actually that is the recommended practice: To have one main ViewModel for the whole page, the main ViewModel could contain ViewModels for the sub views in the page.

Can a view have multiple ViewModels in WPF?

Err no - it's just convention that you have one instance, but there actually aren't any rules that you can't have multiple VM's in the XAML - the key thing to understand is that every item has it's own DataContext (that's inherited), so if you need to use a different DataContext then you just bind to the appropriate VM ...

Can ViewModel have reference view?

Apart from using the name ViewModel (which itself is confusing if the class is full of logic), the one iron-clad rule of MVVM architecture is that you may never reference a View, from ViewModel.


2 Answers

You can take a loot at EventAggragation (mediator pattern)

some other tutorial to start

like image 176
Jordy van Eijk Avatar answered Sep 20 '22 13:09

Jordy van Eijk


There are a few ways to do this depending on how loosely coupled the two view models are. If you have a direct reference to the second view model in your upload view model, then you could pass the data when you display this view model/view.

This seems like the most sensible option if a) the data is a requirement of the second view model and b) the upload view model is responsible for the creation of the second view model. In this case, you could pass the data as a dependency in the constructor of the second view model.

Alternative approaches include using an event aggregator as a mediator to pass the data between the two view models, but I would go with the first approach.

like image 22
devdigital Avatar answered Sep 19 '22 13:09

devdigital