Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding property with parent ViewModel

Tags:

wpf

viewmodel

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?

like image 865
WpfBegnner Avatar asked Sep 10 '13 11:09

WpfBegnner


1 Answers

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

like image 165
Sheridan Avatar answered Oct 20 '22 16:10

Sheridan