Using a ListBox (or other ItemsControl) to host Caliburn presenters

If I have a MultiPresenter and I use a ListBox to display the Presenters that it is hosted on, how do I get Caliburn to detect and link views and view models for items?

For example, if I have a simple view that looks something like this:

 <UserControl x:Class="MyProject.Views.CarView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid> <ListBox ItemsSource="{Binding Parts}" /> </Grid> </UserControl> 

What is related to CarViewModel :

 public class CarViewModel : MultiPresenter { public BindableCollection<IPartViewModel> Parts { get; } } 

And the Parts collection contains various objects that implement IPresenter and have corresponding representations, for example. WheelViewModel and WheelView , and EngineViewModel and EngineView .

I would like Caliburn to allow me views using a viewing strategy. Is it possible? What do I need to do to properly set up the hierarchy of presenters in this case?

+4
source share
1 answer

For this you do not need to change the hierarchy of presenters. I suggest that you consider using the MultiPresenter.Presenters property to collect child ViewModels and the MultiPresenter.Open and MultiPresenter.Shutdown methods if you need to ensure the life cycle of the ViewModels children.

For a binding problem, you must define a template for ListBox items:

 <ListBox ItemsSource="{Binding Parts}"> <ListBox.ItemTemplate> <DataTemplate> <ContentControl cal:View.Model="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

Using the attached cal:View.Model , the structure takes care of creating the corresponding View for each ViewModel, binding it to the ViewModel and inserting it into the ContentControl.

You must also ensure that your namespace and classspace for the Views and ViewModels names follows the Caliburn default convention , if you want your views to be correctly derived from the base. Otherwise, you need to write a custom IViewStrategy (it's not difficult, though).


Edit: fixed binding expression in cal: View.Model property

+8
source

All Articles