Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTemplate.DataType alternative in Silverlight

I have a view model with a property Fields which is an ObservableCollection<FieldVM>. In the view that uses this property, I have an ItemsControl like so:

...
<ItemsControl ItemsSource="{Binding Fields}" />
...

FieldVM is an abstract class, implemented by such classes as TextFieldVM and EnumFieldVM. During run time, these FieldVM-implementations get added to the Fields property and I want them to show up in my view with their associated views.

In WPF, doing this is simple, I do it all the time. You just do this in an appropriate resource dictionary, and everything works as expected:

<DataTemplate DataType="{x:Type vm:TextFieldVM}">
    <v:TextFieldView />
</DataTemplate>

<DataTemplate DataType="{x:Type vm:EnumFieldVM}">
    <v:EnumFieldView />
</DataTemplate>

Now, working in Silverlight for the first time, I expected I could just do the same thing, but the DataTemplate doesn't have a DataType property. I'm stumped. What's the Silverlight-way of doing this?

like image 237
Alex Avatar asked Mar 08 '10 10:03

Alex


1 Answers

Microsoft Prism library has custom DataTemplateSelector implementation, notice Classnames in DataTemplate x:keys:

                    <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <prism:DataTemplateSelector Content="{Binding}" HorizontalContentAlignment="Stretch" IsTabStop="False">
                            <prism:DataTemplateSelector.Resources>
                                <DataTemplate x:Key="OpenQuestionViewModel">
                                    <Views:OpenQuestionView DataContext="{Binding}"/>
                                </DataTemplate>

                                <DataTemplate x:Key="MultipleSelectionQuestionViewModel">
                                    <Views:MultipleSelectionView DataContext="{Binding}"/>
                                </DataTemplate>

                                <DataTemplate x:Key="NumericQuestionViewModel">
                                    <Views:NumericQuestionView DataContext="{Binding}"/>
                                </DataTemplate>
                            </prism:DataTemplateSelector.Resources>
                        </prism:DataTemplateSelector>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
like image 93
Ben Avatar answered Oct 28 '22 23:10

Ben