有没有办法在 WPF 中使用数据模板继承? [英] Is there a way to use data-template inheritance in WPF?

查看:30
本文介绍了有没有办法在 WPF 中使用数据模板继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以具有 DataTemplate 组合或继承(类似于样式中的BasedOn")?有 2 个实例是我需要的.

Is it possible to have DataTemplate composition or inheritance (similar to "BasedOn" in Styles)? There are 2 instances where I need that.

  1. 对于继承类:我有一个包含多个继承类的基类.我不想在每个派生类的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆