Caliburn.Micro: Create and Bind View programmatically
Asked Answered
G

2

8

I am currently experimenting with view composition in Caliburn.Micro. I have a working example where I have multiple user control based views injected into my main shell via the "View.Model" attached property route. So far so good.

In my application proper I am working with a mixed environment of mainly WinForms, with some WPF, so there is no WPF "shell" for Caliburn to manage. I'd like to be able to create my views on demand and add them to placeholders in my WinForms app.

I would like to know how I go about creating a view (which will be a user control containing sub user controls) programmatically using Caliburn so that all conventions, model bindings and sub-view injection is carried out.

Gunslinger answered 13/6, 2011 at 16:6 Comment(0)
G
14

The Caliburn ViewModelBinder can be used to crank the handle once you have a view instance and a corresponding view-model. Calling Bind resolves injected views and applies convention based binding, etc:

    SomeCompositionView view = new SomeCompositionView();

    ISomeCompositionViewModel viewModel = IoC.Get<ISomeCompositionViewModel>();

    ViewModelBinder.Bind(viewModel, view, null);

    ElementHost.Child = view;  
Gunslinger answered 13/6, 2011 at 17:11 Comment(1)
One thing though, it does not call Initialize/Activate/Deactivate if you do it like this.Bridie
R
13

Code snippet from BootstrapperBase.DisplayRootViewFor:

var viewModel = IoC.GetInstance(viewModelType, null);
var view = ViewLocator.LocateForModel(viewModel, null, null);

ViewModelBinder.Bind(viewModel, view, null);

var activator = viewModel as IActivate;
if(activator != null)
    activator.Activate();
Rueful answered 19/6, 2015 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.