有没有一种方法可以在WPF中使用数据模板继承? [英] Is there a way to use data-template inheritance in WPF?
问题描述
是否可能具有 DataTemplate
组成或继承(类似于样式中的 BasedOn)?有两种情况需要。
Is it possible to have DataTemplate
composition or inheritance (similar to "BasedOn" in Styles)? There are 2 instances where I need that.
-
对于继承的类:我有一个带有几个继承的类的基类。我不想在每个派生类的
DataTemplate
中复制基类模板。
不同的视图:对于同一个类,我想定义一个数据模板,然后根据需要添加到该模板中。例如基本模板将显示对象中的数据,然后我希望在显示数据(继承基本模板)的同时可以对对象执行不同操作的不同模板。
Different Views: for the same class I want to define a datatemplate, and then add to that template as appropriate. Ex. the base template will display the data in the object and then i want different templates that can perform different actions on the object, while displaying the data (inheriting the base template).
推荐答案
我发现唯一要做的事情是这样的:
The only thing that I have found do to for this kind of thing is this:
<DataTemplate x:Key="BaseClass">
<!-- base class template here -->
</DataTemplate>
<DataTemplate DataType="{x:Type app:BaseClass}">
<ContentPresenter Content="{Binding}"
ContentTemplate="{StaticResource BaseClass}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type app:DerivedClass}">
<StackPanel>
<ContentPresenter Content="{Binding}"
ContentTemplate="{StaticResource BaseClass}"/>
<!-- derived class extra template here -->
</StackPanel>
</DataTemplate>
基本上,这会创建一个可以使用键引用的通用模板(在这种情况下为BaseClass) 。然后,我们为基类和任何派生类定义实际的DataTemplate。然后,派生的类模板将添加它自己的东西。
Basically this creates a "common" template that can be referenced using a key (BaseClass in this case). Then we define the real DataTemplate for the base class, and any derived classes. The derived class template would then add it's own "stuff".
在 msdn 前一段时间,但没有人想出一个我看到的更好的解决方案。
There was some discussion about this on msdn a while back, but no one came up with a better solution that I saw.
这篇关于有没有一种方法可以在WPF中使用数据模板继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!