开发者

WPF: Applying multiple data templates?

开发者 https://www.devze.com 2023-04-11 12:05 出处:网络
Let\'s say I am displaying a data component, such as TreeView. Let\'s say it is bound to a tree structure, of base type TreeViewItem.

Let's say I am displaying a data component, such as TreeView.

Let's say it is bound to a tree structure, of base type TreeViewItem.

TreeViewItem
    TreeViewItem
    TreeViewItem
        TreeViewItem

and so on.

But some of those items are more specific implementations of TreeViewItem such as AnimalTreeViewItem and even more granular ZebraTreeViewItem

TreeViewItem
    AnimalTreeViewItem
        ZebraTreeViewItem
    PlantTreeViewItem

Now, let's say i want these items to be rendered in a similar fashion, but there would be slight differences in rendering depending on underlying type.

One way i've gotten this to work, is using DataTemplate.

Problem is that i have to create a separate template for each type, with 100% of contents defined in the same way (minus small difference in layout / color etc)

Is there a way to define data templates, that share most of their contents together? meaning, w/out having to create 2 templates, that are almost i开发者_Go百科dentical in their markup, just to change the background color of some textbox etc..


You might be interested in the solution shown in this article. It works fine if the differences between are minor, e.g. a different color for some element, but it can also handle more complex scenarios through the use of triggers.


The answer to this question is DataTriggers

<DataTemplate x:Key="myTaskTemplate">
  ...
<DataTemplate.Triggers>
  <DataTrigger Binding="{Binding Path=TaskType}">
    <DataTrigger.Value>
      <local:TaskType>Home</local:TaskType>
    </DataTrigger.Value>
    <Setter TargetName="border" Property="BorderBrush" Value="Yellow"/>
  </DataTrigger>
</DataTemplate.Triggers>
  ...
</DataTemplate>

This data template will only be 'triggered' when the TaskType is Home.

http://msdn.microsoft.com/en-us/library/ms742521.aspx#adding_more_to_datatemplate

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号