views:

22

answers:

2

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...

+1  A: 

You can use a DataTemplateSelector for that case.

MrDosu
+2  A: 

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

Thomas Levesque