First, in template is better to use the ContentPresenter
, instead of ContentControl
, which is a common practice. Quote reply Nir
(Question: What's the difference between ContentControl and ContentPresenter?):
ContentControl is a base class for controls that contain other elements and have a Content-property (for example, Button).
ContentPresenter is used inside control templates to display content.
ContentControl, when used directly (it's supposed to be used as a base class), has a control template that uses ContentPresenter to display it's content.
Inside ControlTemplate use ContentPresenter;
Outside of ControlTemplate (including DataTemplate and outside templates) try not to use any of them, if you need to, you must prefer ContentPresenter;
Subclass ContentControl if you are creating a custom "lookless" control that host content and you can't get the same result by changing an existing control's template (that should be extremely rare).
Second, the type of construction:
<Expander Header="MyHeader">
<Expander.Content>
<TextBlock Text="Content"/>
</Expander.Content>
</Expander>
You automatically overwrites your the template (style)
, so the color is the same everywhere, because Red
is set, taken from the Style setter
.
So, a slightly modified example:
<Style TargetType="{x:Type Expander}">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Expander}">
<StackPanel>
<Border BorderThickness="{TemplateBinding BorderThickness}" TextBlock.Foreground="{TemplateBinding Foreground}">
<ContentPresenter Content="{TemplateBinding Header}" />
</Border>
<Border Name="Content" BorderThickness="{TemplateBinding BorderThickness}" TextBlock.Foreground="Blue">
<ContentPresenter Content="{TemplateBinding Content}" />
</Border>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Grid>
<!-- Work -->
<Expander Header="MyHeader" Content="MyContent" />
<!-- Not work -->
<!--<Expander Header="MyHeader">
<Expander.Content>
<TextBlock Text="Content"/>
</Expander.Content>
</Expander>-->
</Grid>
To study the work style, you can take a predefined style (such as MSDN), and change it from there.
Note:
It is better to design a universal template to the content, because if you set the content other than TextBlock
, color for TextBlock
will be useless. Perhaps it is better to set the color in style for the TextBlock
.