I am using Caliburn Micro in my Project and i have many UserControls and thier viewmodel inherited from PropertyChangedBase, i want this UserControl to be added to a Canvas in my ShellView. I dont want to use IWindowManager from showing Windows instead i want them to get added in a Canvas.
Please help. How can i do that.
If you use
ContentControlwithin yourShellViewyou can hook into the View-ViewModel binding process of Caliburn.Micro.I assume that in your
ShellViewModelyou have a bunch of properties exposed that are types ofViewModel. If you place aContentControlin yourShellView(this could be on/as a child ofCanvasif that is the container you wish to use to layout your Shell), and then name that control with the name of the property in yourShellViewModelyou wish it to be bound to, then Caliburn’sViewModelBinderwill do the rest for you.As an example say you have a VM called
FizzViewModeland a matching View calledFizzView(which is just aUserControl) and you wantFizzViewto appear on yourShellViewyou could do something like the following…A stripped back
ShellViewModelAnd its matching
ShellViewHere because the
ContentControlis named TheFizz, it will be bound by Caliburn to the property with that name on your VM (the one of typeFizzViewModel)Doing this means you don’t have to laydown your
UserControl‘s using their true types on yourShellView, you let Caliburn do the work for you via conventions (which all so means its easy to swap out the type TheFizz if you just add a little more interface indirection).UPDATE
From the extra information you have provided in the comments, I can now see you are actually looking at a problem that requires an ItemsControl.
The default
DataTemplateCaliburn uses looks like the followingYou will notice that it uses a
ContentControl, which has some advantages as I have discussed above. Basically what this will do is allow Caliburn to provideDataTemplateSelectorlike behaviour to the items in yourItemsControl. So you can add VMs of different types to the collection yourItemsControlis bound to and this defaultDataTemplatewill resolve the type of View to use to display it. The following demos a very simple example of how you can achieve what you want.First the ShellViewModel, take note of the
BindableCollectionnamed ItemsAnd then a few dummy VM types that you want to display in your Shell. These could be/do anything you like:
Now a ShellView, note the ItemsControl which binds to the Items property on your ShellViewModel
And an example of a
UserControlthat will be used to display theGreenViewModel, create 2 more of these, changing the names toRedViewandBlueViewand set the backgrounds appropriately to get the demo to work.What this example does when put together is creates colored squares on the
Canvasof your shell based on the location of the mouse click. I think you should be able to take this and extend it to your needs.