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

2

6

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.

Alanaalanah answered 3/10, 2014 at 13:33 Comment(0)
N
8

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;
Nonrecognition answered 3/10, 2014 at 13:37 Comment(1)
Ah yes, of course. Totally forgot about that property. Thank you!Alanaalanah
A
2

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.

Andra answered 11/7, 2016 at 14:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.