tags:

views:

232

answers:

1

If I have a MultiPresenter and I am using a ListBox to display the Presenters it is hosting, how do I get Caliburn to discover and bind the views and view models for the 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"&gt;
    <Grid>
        <ListBox ItemsSource="{Binding Parts}" />
    </Grid>
</UserControl>

Which is bound to the CarViewModel:

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

And the Parts collection contains various objects that implement IPresenter and have corresponding views, e.g. WheelViewModel and WheelView, and EngineViewModel and EngineView.

I'd like Caliburn to resolve the views for me using the view strategy. Is this possible? What do I need to do to correctly set up the hierarchy of presenters in this case?

+2  A: 

You don't have to change presenter hierarchy for this. I only suggest you to consider using the MultiPresenter.Presenters property to collect child ViewModels and the MultiPresenter.Open and MultiPresenter.Shutdown methods if you need to enforce child ViewModels lifecycle.

For the binding issue, you should define the template for the ListBox items:

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

Using al:View.Model attached property, the framework takes care of creating an appropriate View for each ViewModel, binding it to the ViewModel and injecting it into the ContentControl.

You should also make sure that your namespace and class naming for Views and ViewModels follows the Caliburn default convention if you want your Views to be correctly inferred by the framework. Otherwise, you have to write a custom IViewStrategy (it's not hard, though).


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

Marco Amendola
I think the correct ContentControl looks like this: <ContentControl cal:View.Model="{Binding .}" />
GraemeF
You are true. Actually, the dot is superfluous.Sorry for the mistake, and thank you for pointing out.
Marco Amendola