Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caliburn.Micro: Create and Bind View programmatically

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.

like image 968
Tim Lloyd Avatar asked Jun 13 '11 16:06

Tim Lloyd


2 Answers

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;  
like image 173
Tim Lloyd Avatar answered Oct 21 '22 13:10

Tim Lloyd


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();
like image 29
xmedeko Avatar answered Oct 21 '22 12:10

xmedeko