WPF MVVM and nested Views with dependency properties
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 DataContext
s).
It seems like I'm missing something obvious...
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.
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.
链接地址: http://www.djcxy.com/p/56214.html上一篇: Wpf UserControl和MVVM
下一篇: WPF MVVM和具有依赖属性的嵌套视图