Question

I have a parent view that defines a child view in Xaml. The child view has a DependencyProperty that is bound to the parent view's ViewModel. However, that value is also needed by the child view's ViewModel.

<custom:Parent>
  <custom:Child ChildId="{Binding ParentFooId}" ... />
</custom:Parent>

ChildId is implemented as a dependency property of the ChildView control. If the ChildViewModel needs ParentFooId, what's the proper MVVM way of obtaining it?

I don't want to cast the DataContext of the ChildView into a ChildViewModel and set value in a OnChildIdChanged handler of the ChildView. That doesn't seem very MVVM-ish to me.

The other alternative I thought of was to create a new ChildViewModel with the value and set it as the DataContext in the OnParentFooIdChanged event (in the ParentViewModel); but that doesn't seem quite right either, since the ViewModels are supposed to be oblivious to the View (and thus don't know anything about DataContexts).

It seems like I'm missing something obvious...

Was it helpful?

Solution

If I understand the question correctly you just need to create the child view model within the parent view model, passing and keeping a reference to the parent view model. That way you can reference any property of the parent view model from the child view model and bind to either in the child view.

OTHER TIPS

If you are simply trying to pass data from a dependency property to your view model I would use the PropertyChangedCallback event. Add a handler that sends the changed data to your View Model. I may be misunderstanding your intent though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top