Use same DataTemplate for different types
Asked Answered
A

2

6

Is it possible to use the same DataTemplate for a defined selection of types, i.e. how to change the following sample code so that the same DataTemplate is used for all listed types?

<DataTemplate DataType="{x:Type local:ClassA, ClassB, ...}">
   <StackPanel Orientation="Horizontal">
      <Label Content="{Binding Path=Title}"/>
      ...
   </StackPanel>
</DataTemplate>
Archaeopteryx answered 15/10, 2012 at 16:1 Comment(0)
T
10

This isn't supported by default, but typically I put the contents of the DataTemplate in a UserControl or another DataTemplate (depends on how complex the template is), and just write a 3-line data template for each class item

<UserControl x:Class="MyUserControl">
   <StackPanel Orientation="Horizontal">
      <Label Content="{Binding Path=Title}"/>
      ...
   </StackPanel>
</UserControl >


<DataTemplate DataType="{x:Type local:ClassA}">
    <local:MyUserControl />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ClassB}">
    <local:MyUserControl />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ClassC}">
    <local:MyUserControl />
</DataTemplate>
Tinkle answered 15/10, 2012 at 16:41 Comment(0)
B
1

It's not supported out of the box, but it would be possible to do something like this by defining custom MarkupExtension. Similar to x:Type extension.

If here, ClassA, ClassB are deriving from same class you should be able to put the base class name here to refer them all.

Bahia answered 15/10, 2012 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.