Is there something in WPF similar to Style.BasedOn for a DataTemplate?

At the moment, I have two very large DataTemplate objects to display two sets of items in two ListBoxes. DataTemplates are referenced in the ContentTemplate property in two styles that are specified in the ItemContainerStyle properties of the two ListBoxes. Elements of the same type and DataTemplates are identical, with the exception of 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 any way to avoid duplicating the entire Dataemplate, but still has this one difference from the text binding of this TextBlock in the second template?

+3
source share
4 answers

(). , DataTemplate, DataTemplates, ContentTemplate ContentPresenter. DataTemplates. .

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

.

+1

, , . , , ..etc (, textstyle2), .

+1

, DataTemplate . , DataTemplate?

Solution: Use another Styleto capture common properties between two templates. You can use it in the same block Resources, if only you need it. This is a much cleaner or easier way to do things.

+1
source

Adding to what Dennis suggested, you can always create a custom control that you simply insert into your DataTemplate and redo that control instead of the DataTemplate.

0
source

Source: https://habr.com/ru/post/1778510/


All Articles