views:

305

answers:

1

I have a WPF application that is made up of a window containing a usercontrol which, in turn, contains another child usercontrol.

I have a dependencyProperty for a SelectedName in my second usercontrol's viewmodel. I want the parent control to be able to either access this property and display the SelectedName in a textblock in the parent control.

I'm a bit stuck as to how to do this.

There seem to be 2 ways I could go (if I understand this correctly) 1. Add an event on the child control and have the event bubble upwards and get handled in the parent. 2. Try and access the child's dependency property directly in the textblock's binding on the parent control.

For either of these ways the thing that I am stuck on is how I get a handle on the control's (either child or parent) datacontext or viewmodel.

Is this a sign that I am heading off on the wrong track or do I need to cast the control's datacontext to the type of viewmodel in question and then use that? Or do I need to share the same viewmodel across both usercontrols?

I'd be grateful for any feedback on this approach - any examples would be really useful as I'm finding I've got a couple of instances of this parent / child control requirement.

Thanks again for your time.

+1  A: 

The view model used for the parent control could have the child control's view model as a property, that way you can directly access it from the parent.

public class ParentViewModel
{
    public ChildViewModel child { get; set; }
}

Then in the xaml, assuming the datacontext is set to the ParentViewModel object, we can easily access the properties from the ChildViewModel...

<TextBlock Text="{Binding Path=child.SomeTextProperty}" />
TabbyCool
Thanks for your comment. Yeah I'd never thought of that! Funny how you can spend hours looking down one route and miss something else entirely.Thanks again!
Jmsparing
Sometimes the most obvious solutions are the ones we need someone else to point out :-)
TabbyCool
could you add some example code?