Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对不同类型使用相同的DataTemplate_C#_Wpf_Datatemplate - Fatal编程技术网

C# 对不同类型使用相同的DataTemplate

C# 对不同类型使用相同的DataTemplate,c#,wpf,datatemplate,C#,Wpf,Datatemplate,是否可以对定义的类型选择使用相同的DataTemplate,即如何更改以下示例代码,以便对所有列出的类型使用相同的DataTemplate <DataTemplate DataType="{x:Type local:ClassA, ClassB, ...}"> <StackPanel Orientation="Horizontal"> <Label Content="{Binding Path=Title}"/> ... &

是否可以对定义的类型选择使用相同的DataTemplate,即如何更改以下示例代码,以便对所有列出的类型使用相同的DataTemplate

<DataTemplate DataType="{x:Type local:ClassA, ClassB, ...}">
   <StackPanel Orientation="Horizontal">
      <Label Content="{Binding Path=Title}"/>
      ...
   </StackPanel>
</DataTemplate>

...

不支持开箱即用,但可以通过定义自定义标记扩展来执行类似操作。与x类似:类型扩展


如果这里的ClassA、ClassB是从同一个类派生的,那么您应该能够将基类名称放在这里来引用它们。

这在默认情况下不受支持,但通常我会将
数据模板的内容放在
用户控件
或另一个
数据模板
中(取决于模板的复杂程度),只需为每个类项编写一个三行数据模板

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

...