views:

25

answers:

1

Hi!

I have searched the net for a way to access an object/property within a UserControl. I have a Page object in my view in wich i load a usercontrol:

<UserControl:RichTextEditorControl Height="350" />

How do i access an object/property which resides in the viewmodel of my view from my usercontrol? To put my problem in practice: i have a list of items that is displayed in my view, and when i have selected an item, i load the usercontrol. I then want my usercontrol to do "stuff" to the selected item. How can i do this?

Thanx!

+1  A: 

You can have the selected item be either a Dependency Property on your UserControl, or just be it's DataContext. You could then just setup the UserControl using binding:

<UserControl1 DataContext="{Binding TheSelectedObjectProperty}" />

If your list box binds to that same TheSelectedObjectProperty, the UserControl will see the selected item when you change items in the list box automatically.

Reed Copsey
Thank you very much for the answer! I guess i should've been more specific, so i wouldnt waste your time, but: the thing is that the user control has its own viewmodel, and in the xaml of the usercontrol, the datacontext is set to that viewmodel. So i guess i cant set the datacontext again.I have tried to make the selected item a dependency property, but i couldnt make it work. I guess there is a possibility that i missed something when trying it though.Thank you!
MrZ
Maybe i should also ask if it is possible to use binding with a relative source and findancestor to get the property?
MrZ
@user409816: If you make the SelectedItem a dependency property, you should be able to setup the binding to it from teh "container" holding the UserControl. That will work fine.
Reed Copsey
@user409816: This, btw, is effectively a master-detail scenario. I also wrote an article showing how to use Behaviors to accomplish this. It might be of use: http://reedcopsey.com/2009/10/14/using-a-behavior-to-aggregate-values-in-a-master-detail-view-in-m-v-vm/
Reed Copsey
I'll definitely look in to this.. thank you very much for your help!
MrZ