Search code examples
c#wpfxamluser-controlsdatatemplate

Select WPF DataTemplate that is determined by type of object


I have a ViewModel that has a List of objects that have the same interface and to show them in the view we have a list of UserControls in our view model that the view binds to. I was wondering if I could create a template for the different types of concrete objects in the list and have WPF apply the correct one for me instead of creating the UserControl list and binding to that.

Basically I have:

<StackPanel 
            Margin="0,0,20,0"
            >                
            <my2:ProfileIdentificationView />
            <ItemsControl
                ItemsSource="{Binding Path=ProfileSections}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
    </DockPanel>

Where the ItemsSource binding is the list of user controls. I am looking for a way to apply the look of those UserControls here based on the type of the ProfileSection. Like one type is an IIS section and another Type is a Users section.


Solution

  • You can create implciit DataTemplates for your view models via the DataTemplate.DataType. Make sure to use the x:Type markup extensions as strings are interpreted as XML-element tags (to allow implicit templating of XML).