Simon
Simon

Reputation: 2345

WPF, Xaml and Controls Factory?

I'd like to create WPF control which consists of few another controls. The main problem is how implement choosing right control depending on Model's type?

<MyControl>
<!-- if DataContext.GetType() == Type1 -->
<Control1 DataContext = {Binding}/>
<!-- if DataContext.GetType() == Type2 -->
<Control2 DataContext = {Binding}>

</MyControl>

How can i implement and design it well? My idea was to put there something like...

Control CreateControl(object dataContext) {
 if (dataContext.GetType() == TYpe1)
     return new Control1() {DataContext = dataContext}
 if (dataContext.GetType() == TYpe2)
     return new Control2() {DataContext = dataContext}    
}

But i don't know how can i invoke such method, which returns Control inside XAML...

Upvotes: 1

Views: 973

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292355

You can define DataTemplates in the resources, and use a ContentControl as a placeholder

Resources:

<DataTemplate DataType="{x:Type model:Model1}">
    <Control1 />
</DataTemplate>

<DataTemplate DataType="{x:Type model:Model2}">
    <Control2 />
</DataTemplate>

(note that you don't need to explicitly set the DataContext)

Usage:

<MyControl>
    <ContentControl Content="{Binding}" />
</MyControl>

It will pick the appropriate DataTemplate based on the type of the Content

Upvotes: 3

MrDosu
MrDosu

Reputation: 3435

You can use a DataTemplateSelector for that case.

Upvotes: 1

Related Questions