Caliburn.Micro: Create and Bind View programmatica

2020-07-10 06:45发布

问题:

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.

回答1:

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;  


回答2:

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();