Is there something in WPF similar to Style.BasedOn

2019-07-05 14:27发布

At the moment, I have two very large DataTemplate objects to display two sets of items in two ListBoxes. The DataTemplates are referenced in the ContentTemplate property in two Styles that are set in the ItemContainerStyle properties of the two ListBoxes. The items are of the same type and the DataTemplates are identical except for the following control:

From DataTemplate1

<TextBlock Style="{StaticResource TextStyle}" FontSize="20" Foreground="White"
HorizontalAlignment="Left" Panel.ZIndex="2" Text="{Binding RemainingTime.TotalHours,
Converter={StaticResource DoubleToIntegerConverter}, StringFormat={}{0:#00}}" />

From DataTemplate2

<TextBlock Style="{StaticResource TextStyle}" FontSize="20" Foreground="White"
HorizontalAlignment="Left" Panel.ZIndex="2" Text="{Binding ElapsedTime.TotalHours,
Converter={StaticResource DoubleToIntegerConverter}, StringFormat={}{0:#00}}" />

Is there some way to avoid duplicating the whole Dataemplate but still have this one difference in the text binding of this TextBlock in the second template?

4条回答
爷的心禁止访问
2楼-- · 2019-07-05 14:32

No, there is no inheritance for DataTemplate. If you think about, how would you override a part of a DataTemplate?

Solution: Use another Style to capture the common properties between the two templates. You can scope it in the same Resources block if it only place you need it. It is much cleaner or more WPF way of doing things.

查看更多
甜甜的少女心
3楼-- · 2019-07-05 14:41

Adding to what Dennis suggested, you can always create a custom control that you just stick inside your DataTemplate and re-style that control instead of the DataTemplate.

查看更多
看我几分像从前
4楼-- · 2019-07-05 14:42

I've already asked this question here once and unfortunately there isn't. but in this specific situation you can move the fontsize,foreground,horizontalalignment..etc to a style (lets say textstyle2) that based on your current textstyle.

查看更多
Explosion°爆炸
5楼-- · 2019-07-05 14:51

I got an answer to this from another post (by Liz). Basically, you can put all common controls into one DataTemplate and then create two more DataTemplates that each use the first one as a ContentTemplate in a ContentPresenter. Then, you can add different controls into one or both of the latter DataTemplates. Liz provided a code example.

<DataTemplate x:Key="UserTemplate"> 
  <!-- show all the properties of the user class here --> 
</DataTemplate> 
<DataTemplate DataType="{x:Type local:User}"> 
  <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/> 
</DataTemplate> 
<DataTemplate DataType="{x:Type local:Author}"> 
  <StackPanel> 
    <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/> 
    <!-- show all the additional Author properties here --> 
  </StackPanel> 
</DataTemplate>

Thanks once again Liz.

查看更多
登录 后发表回答