Binding property with parent view ViewModel

Refer to How can I pass my DataTemplate to bind to a property in the PARENT ViewModel?

I have a similar problem ... But this solution did not work for me. I have a MainViewModel that has an observable collection of another view model, such as View1 / ViewModel1. This view has a control tree, and I need a context menu for the tree. The main menu has a menu. This main menu and context menu are connected. So, how can I bind context menu commands to the main properties of the viewmodel?

+4
source share
2 answers

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

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

Assuming your parent view has a view model set to its DataContext , this binding will have access to it ... DataContext is a DataContext view, for example. view model defined as DataContext . Therefore, the PropertyName property is a public property of this view model.

Regarding the portion of your question that has been asked so many times, check out the following links (or just search the web):

Context menus in WPF

Binding ContextMenu to its logical parent

+11
source
 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 ie 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"/> 
0
source

Source: https://habr.com/ru/post/1501449/


All Articles