Search code examples
wpfxamlcode-behindcaliburn.microcaliburn

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.


Solution

  • 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;