I stuck in very strange problem and I could not find solution to it. I tried almost all the possible ways (even delete and recreate solution) to solve this.
ISSUE
I am trying to override default style of control in a WPF app. I defined all the resouces and styles in App.xaml
. Problem is, a button foreground color is not getting override runtime. Suprisingly, it show overriden color (White) in VS designer but when I run app, it becomes black (may be default).
There is no other code in app that changes button style.
Additional Info : Buttons are in a Usercontrol and its loaded on MainWindow's ContentControl.
<SolidColorBrush x:Key="WhiteBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="BlackBrush" Color="#000000"/>
<SolidColorBrush x:Key="ActiveBrush" Color="#3A71C5"/>
<SolidColorBrush x:Key="HoverBrush" Color="#0071C5"/>
<SolidColorBrush x:Key="PressBrush" Color="#3A8BF4"/>
<SolidColorBrush x:Key="DefaultBrush" Color="#0071F9"/>
<SolidColorBrush x:Key="DisabledBrush" Color="#F4F4F4"/>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="{StaticResource ActiveBrush}"/>
<Setter Property="Foreground" Value="{StaticResource WhiteBrush}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource HoverBrush}"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{StaticResource PressBrush}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" Value="{StaticResource DisabledBrush}"/>
</Trigger>
</Style.Triggers>
</Style>
Buttons in VS Designer
Buttons in app runtime
The issue could be that you have some other style which gets applied to some nested control of your button (e.g. TextBlock
).
I pasted your snippet in a sample WPF app and wrapped a Button
in a custom UserControl
. I tested it and showed correctly in both design view and runtime.
Then I added the following style in App.xaml
:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Red"/>
</Style>
and the button was showing red text.
So the problem could be some other style for other controls which is overriding some parts of your Button
template.
EDIT
A possible solution could be to explicitly define the Button content in the control itself:
<Button>
<TextBlock Foreground="{StaticResource WhiteBrush}">Test</TextBlock>
</Button>
There are probably more elegant ways to do this, but I couldn't come up with anything else at the moment.