Binding property with parent ViewModel

£可爱£侵袭症+ 提交于 2019-11-29 08:03:26

Basically, you need to use a RelativeSource binding. The standard way is to find an ancestor (or parent) of the control of a particular type:

{Binding DataContext.PropertyName, RelativeSource={RelativeSource FindAncestor, 
    AncestorType={x:Type YourViewsNamespace:YourParentView}}}

Assuming that your parent view has a view model set to its DataContext, this binding will access it... the DataContext is the DataContext of the view, eg. the view model that is set as the DataContext. So, the PropertyName property is a public property from that view model.

Regarding the part of your question that has been asked so many times before, please see the following links (or just search online):

Context Menus in WPF

Binding ContextMenu to its logical Parent

1. ParentViewModel has NavigateRecordCommand

2. Parentview has the DataContext Set to my ParentViewModel.

<UserControl x:Class="SampleProject.UI.ParentView"

<Grid>
    ....
<!--User control is here-->
    <local:NavigationControl  Grid.Row="1" />
    ....
</Grid>


3. Child Control as below. Not bounded to its ViewModel. Bounded to Parent Views DataContext i.e. ParentViewModel.

    <UserControl x:Class="SampleProject.UI.NavigationControl"
    ...
    ...
     xmlns:Local="clr-namespace:SampleProject.UI">

    <Button Command="{Binding DataContext.NavigateRecordCommand, RelativeSource={RelativeSource AncestorType=Local:ParentView}}"
            CommandParameter="MoveFirst"/>        
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!