views:

88

answers:

2

I'm working on a problem right now where I need to embed a UserControl inside another UserControl. But, I need to determine at runtime which embedded UserControl to instantiate.

This implies to me that some form of data binding and/or template selection mechanism has to be invoked, but I'm not sure how to proceed with the pure XAML approach.

If I was to do this with code, I would define some sort of container control in the parent UserControl, and then in the code-behind, implement some logic which would instantiate the appropriate child UserControl and then insert it as Content into the specified container in the parent UserControl.

Can this be done using only XAML, or is some sort of code-behind required?

+1  A: 

I assume you are starting with WPF, If I am right, what you want here more of an ItemsControl in XAML and set ItemsSource(Collection of DataObjects) to it, Then define ItemsControl.ItemsTemplate to give appropriate DataTemplate of the DataObject. Rest is all driven by the data and you dont need to worry about any instantiation, WPF will do all those visual creation.

Jobi Joy
Thanks, I'll take a look at this.It seems a little counter-intuitive, though...
kmontgom
A: 

If the choice of the child UserControl is based on the type of the DataContext, the best way to do it is to use a ContentControl with several DataTemplates in the resources :

<ContentControl Content="{Binding SomeProperty"}>
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type local:Foo}">
            <local:UserControlForTypeFoo />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:Bar}">
            <local:UserControlForTypeBar />
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>

The ContentControl will pick the appropriate DataTemplate based on the type of SomeProperty. That's the way it's usually done in MVVM

Thomas Levesque
This looks much closer to what I'm looking for. Thanks.
kmontgom