I have a button and I want to change the background color of button. but when I set the background property to a color like blue:
<Button Width="75" Height="25" Margin="6" Background="Blue"/>
and when the button has focus, the color changes in white and my color.
How can I set this white color to another color?
I believe that your problem is caused by the default ControlTemplate
for the Button
control. The colour animations that you describe are defined in this ControlTemplate
and so you need to provide your own ControlTemplate
to remove this behaviour:
<Button Content="Click Me" Background="Blue">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Border Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
<ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="{TemplateBinding Padding}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsFocused" Value="True">
<Setter TargetName="Border" Property="Background" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
First Solution is
<Style x:Key="BtnStyle" TargetType="Button">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid x:Name="gd" Height="120" Width="120" Background="{TemplateBinding Background}">
<ContentPresenter></ContentPresenter>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsFocused" Value="True">
<Setter Property="Background" Value="White" TargetName="gd"></Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Visibility" Value="Collapsed" TargetName="gd"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Button Width="75" Style="{StaticResource BtnStyle }" Content="ok" Height="25" Background="Blue"/>
second solution
<Style x:Key="Button_focusvisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Border SnapsToDevicePixels="True" Background="White">
<TextBlock Text="Ok" ></TextBlock>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Button Width="75" FocusVisualStyle="{StaticResource Button_focusvisual }" Content="ok" Height="25" Background="Blue"/>