Alvin Santos
Alvin Santos

Reputation: 87

How can I pass data from usercontrol to another usercontrol using mvvm

For example I have a mainwindow that has a frame on it which binds to a model of all user controls that I have.

Example: (Basic Personal Information)

I have a usercontrol or (view-1) that display single person from my personalInformation database.

and I also have a usercontrol or (view-2) that display all the list of person in my database.

the question is how can I get the ID of single person from (view-2) to (view-1) as they are different usercontrol and different viewmodel as well.

what is the best approach to this kind of scenario? TIA.

Upvotes: 1

Views: 3984

Answers (1)

Ramin Bateni
Ramin Bateni

Reputation: 17425

A

The Usercontrols are some elements to be part of your Window, then the Window can be the suitable connector between your UserControls. you can approach this scenario like this:

  1. WindowA
  2. UserControlPersonList
    • Include SelectedPersion Dependency Property. SelectedPerson type is a model class or viewmodel class
  3. UserControlPerson

Now, inside WindowA.xaml:

<StackPanel>
    <userControls:UserControlPersonList x:Name="PersonListControl"/>

    <userControls:UserControlPerson DataContext="{Binding ElementName=PersonListControl, Path=SelectedPerson}"/>
</StackPanel>

The result can be something like this (a master-detail view):

enter image description here

You need fill SelectedPerson dependency property of UserControlPersonList when you select a person. To perform this you can use Command and change SelectedPerson property in PersonListViewModel and bind SelectedPerson dependency property in UserControlPersonList to it OR do this in your UserControlPersonList level like this answer.


B

But if you want some global changed in your UserControls in different Windows you can hold the PersonListViewModel in a static property that is accessible in all of your Windows and Usercontrols of your program then create an event in it named SelectedPersionChanged. Now in your UserControls you can subscribe an EventHandler to SelectedPersionChanged and change your DataContext. But you MUST unsubscribe your EventHandler from SelectedPersionChanged when you did not need to that UserControl anymore to prevent memory leaks.

Upvotes: 3

Related Questions