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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With