kmontgom
kmontgom

Reputation: 1429

Selecting a UserControl from XAML

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?

Upvotes: 2

Views: 416

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292615

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

Upvotes: 1

Jobi Joy
Jobi Joy

Reputation: 50038

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.

Upvotes: 1

Related Questions