Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM - Proper way to call method in "parent" View Model

Tags:

c#

mvvm

wpf

I'm working on a project in WPF-MVVM where I have a Main Window that contains a Tab Control with two tabs. Each of these tabs has a button on it.

In this project, there are 3 different View Models, one for the Main Window and one for each of the tabs. When one of the buttons is pressed, I would like the "parent" view model (the View Model for the Main Window) to perform some action, such as closing the application.

What is the proper way to go about having the View Model for the Tabs ask the Main View Model to perform this action?

Screenshot of Application

Code on Pastebin

Note: I am not using any sort of framework such as MVVM Light or Prism.

like image 343
Everix Avatar asked Sep 16 '25 07:09

Everix


1 Answers

You could access the parents DataContext by using a relative binding like this:

Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
    AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}"
like image 101
devmb Avatar answered Sep 17 '25 22:09

devmb