Reputation: 87
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
Reputation: 17425
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:
WindowA
UserControlPersonList
SelectedPersion
Dependency Property. SelectedPerson
type is a model class
or viewmodel class
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):
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.
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