Special thanks to @BionicCode for getting me started here with my user control styling: Styling A Custom Control
I created a simple demo custom control with a button and textblock. Now I'm adding a style for the button.
First, I added a ComponentResourceKey in the code file:
public static ComponentResourceKey ButtonStyleKey = new ComponentResourceKey(typeof(MyCustomControl), "ButtonStyle");
Next, I added the button style to my Generic.xaml file
<Style x:Key="{x:Static local:MyCustomControl.ButtonStyleKey}"
TargetType="{x:Type Button}">
<Setter Property="Background" Value="#EEEEEEEE"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="10 5"/>
<Setter Property="FontSize" Value="14" />
<Setter Property="BorderThickness" Value="2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Border x:Name="Border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"/>
<ContentPresenter x:Name="content"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="Margin" Value="2 1" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Orange"/>
<Setter Property="Foreground" Value="Blue"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="Gray"/>
<Setter Property="Foreground" Value="DarkGray"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
Here's the button in the control template
<Button Grid.Row="0"
x:Name="button"
Height="65"
Width="150"
Content="A Button"
Style="{DynamicResource {x:Static local:MyCustomControl.ButtonStyleKey}}"/>
The problem is with the IsPressed trigger. The background color does not change to red.
The MouseOver trigger works fine and sets the button's background to orange, and the IsEnabled trigger sets the colors for disabled as well, so I know the style is working ok otherwise.
DynamicResourceis very expensive. You should avoid it and only use it if you dynamically replace the referenced resource at runtime. Always preferStaticResource. There are many reasons to avoidDynamicResource. For example, in your case the resource is in the themes resource dictionary. This means, any exception that are caused by this resource will be thrown at runtime. For this reason, you should also consider declaring the resource in the application resource dictionary instead.