Inheriting ContentElement ContentPresenter Properties

I have a generic DataTemplate, NameTemplate , which I use inside other DataTemplates. I intentionally left the FontSize and FontFamily properties undefined so that the consuming DataTemplate could set the attached TextElement properties and have the NameTemplate TextBlock inherit these properties.

The problem is that the TextBlock inside the NameTemplate does not inherit those nested TextElement properties. See the code below and my working solution to the problem.

I am sending a message to find out if there is a better way to solve this and possibly explain why my solution works? In addition, at the end of this post we are talking about another problem that I encountered with this solution.

Here is the NameTemplate ;

<DataTemplate x:Key="NameTemplate" DataType="{x:Type common:Contact}">
    <TextBlock>
        <Run Text="{Binding Title, Mode=OneWay}"/>
        <Run Text="{Binding FirstName, Mode=OneWay}"/>
        <Run Text="{Binding MiddleInitial, Mode=OneWay, TargetNullValue='', FallbackValue='', StringFormat='{}{0}. '}"/><Run Text="{Binding LastName, Mode=OneWay}"/>
    </TextBlock>
</DataTemplate>

Here is an example of a consumed DataTemplate;

<DataTemplate DataType="{x:Type common:Contact}">
    <StackPanel>
        <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource NameTemplate}" Style="{StaticResource SubHeadingTextElementStyle}"/>
        <!-- Other Template Stuff -->
    </StackPanel>
</DataTemplate>

The SubHeadingTextElementStyle style is as follows;

<Style x:Key="SubHeadingTextElementStyle" BasedOn="{StaticResource DefaultTextElementStyle}">
    <Setter Property="TextElement.FontFamily" Value="{telerik:Windows8Resource ResourceKey=FontFamily}"/>
    <Setter Property="TextElement.FontSize" Value="{telerik:Windows8Resource ResourceKey=FontSizeL}"/>
</Style>

To make this work as intended, I need to add the following bindings to the NameTemplate TextBlock;

<DataTemplate x:Key="NameTemplate" DataType="{x:Type common:Contact}">
    <TextBlock FontSize="{Binding (TextElement.FontSize), RelativeSource={RelativeSource Self}}" FontFamily="{Binding (TextElement.FontFamily), RelativeSource={RelativeSource Self}}" 
               Foreground="{Binding (TextElement.Foreground), RelativeSource={RelativeSource Self}}" FontWeight="{Binding (TextElement.FontWeight), RelativeSource={RelativeSource Self}}">
        <Run Text="{Binding Title, Mode=OneWay}"/>
        <Run Text="{Binding FirstName, Mode=OneWay}"/>
        <Run Text="{Binding MiddleInitial, Mode=OneWay, TargetNullValue='', FallbackValue='', StringFormat='{}{0}. '}"/><Run Text="{Binding LastName, Mode=OneWay}"/>
    </TextBlock>
</DataTemplate>

Note the binding of the RelativeSource bindings to the attached TextElement.

, , TextElement.FontWeight BooleanToFontWeightConverter - , Convert , , , , .

+4

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


All Articles