Reputation: 1953
I would like to create a ControlTemplate. Text in the ContentPresenter must be styled, but dont. How to style textblock in contentpresenter? This is my code:
<Style x:Key="PrimaryPanel" TargetType="GroupBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="GroupBox">
<Border BorderThickness="1" BorderBrush="#337AB7">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Background="#337AB7">
<ContentPresenter ContentSource="Header">
<ContentPresenter.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="#fff"></Setter>
<Setter Property="Margin" Value="0 -1 0 0"></Setter>
<Setter Property="Padding" Value="5"></Setter>
<Setter Property="VerticalAlignment" Value="Center"></Setter>
</Style>
</ContentPresenter.Resources>
</ContentPresenter>
</StackPanel>
<Border Grid.Row="1" Padding="10 5" Margin="5 0 5 10" >
<StackPanel>
<ContentPresenter />
</StackPanel>
</Border>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Using:
<GroupBox Style="{StaticResource PrimaryPanel}">
<GroupBox.Header>
<TextBlock Text="Title"/> this text must by styled
</GroupBox.Header>
</GroupBox>
Thanks for advice.
Upvotes: 1
Views: 1317
Reputation: 3787
I've created a simple behavior for you that resolves your issue pretty well:
public class Behaviour
{
public static object GetStyleToLoad(DependencyObject obj)
{
return (object)obj.GetValue(StyleToLoadProperty);
}
public static void SetStyleToLoad(DependencyObject obj, object value)
{
obj.SetValue(StyleToLoadProperty, value);
}
// Using a DependencyProperty as the backing store for StyleToLoad. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StyleToLoadProperty =
DependencyProperty.RegisterAttached("StyleToLoad", typeof(object), typeof(Behaviour), new PropertyMetadata(null,
(o, e) =>
{
if (e.NewValue != null)
{
Style s = e.NewValue as Style;
if (s != null)
{
FrameworkElement fe = o as FrameworkElement;
if (fe != null)
{
fe.Resources.Add(s.TargetType, s);
}
}
}
}));
}
Usage:
In my View I put a TextBlock Style with HotPink Foreground:
<UserControl.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground"
Value="HotPink" />
</Style>
Applying of the Behaviour for your ContentPresenter:
<ContentPresenter local:Behaviour.StyleToLoad="{StaticResource {x:Type TextBlock}}"
Content="My Text" />
There the result after compilation:
As you can see the Style has been applied.
Upvotes: 2