Binding property with parent ViewModel
Asked Answered
S

2

10

Please refer to How can I tell my DataTemplate to bind to a property in the PARENT ViewModel?

I have similar problem... But this solution didn't work for me. I have a MainViewModel which has an observable collection of another view model say View1/ViewModel1. This view has a tree control and I need context menu for the tree. My main view has a menu. Those main menu and context menu are connected. So how can I bind the context menu commands to the main viewmodel's properties?

Sectarianism answered 10/9, 2013 at 11:4 Comment(0)
M
23

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

Monachism answered 10/9, 2013 at 11:51 Comment(1)
I have tried your solution..But it didnt give me the answer. I gone through your refernce sites also..But they too didnt help me. I tried in the following way............ <ContextMenu > <MenuItem x:Name="CopyItem" Header="Copy" Command="{Binding DataContext.CopyCmnd, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Views:MainPanel}}}" /> </ContextMenu>Sectarianism
F
0
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"/>        
Fredrika answered 2/10, 2014 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.