Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caliburn.Micro, how to access the actual viewmodel used from within the view

I want to access the actual viewmodel that is currently used from within the view (code-behind). In the bootstrapper I have the viewmodel set to perrequest so I cannot use IoC.Get<..ViewModel>(); (nor do I want to change this behavior).

Basically, I'm looking for the equivalent of the GetView from the Screen, but then the other way around.

like image 711
The Cookies Dog Avatar asked Oct 03 '14 13:10

The Cookies Dog


2 Answers

DataContext will give you the current ViewModel which is applied as DataContext of view.

// Get you the object of ViewModel.
var viewModelInstance = DataContext;

// Or typecast to exact instance what you intend to use.
MyViewModel vm = DataContext as MyViewModel;
like image 198
Rohit Vats Avatar answered Nov 15 '22 11:11

Rohit Vats


Bear in mind that the DataContext will have a value assigned to it once the View has been loaded. For example you can access to it in the loaded event of the View.

like image 35
Sebastian Inones Avatar answered Nov 15 '22 12:11

Sebastian Inones