当它具有焦点时,更改wpf中按钮的背景

时间:2014-01-06 12:08:57

标签: c# wpf button

我有一个按钮,我想更改按钮的背景颜色。但是当我将background属性设置为蓝色的颜色时:

<Button Width="75" Height="25" Margin="6" Background="Blue"/>

当按钮具有焦点时,颜色会变为白色和我的颜色。

如何将此白色设置为其他颜色?

2 个答案:

答案 0 :(得分:6)

我认为您的问题是由ControlTemplate控件的默认Button引起的。您描述的颜色动画在此ControlTemplate中定义,因此您需要提供自己的ControlTemplate来消除此行为:

<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>

答案 1 :(得分:0)

第一个解决方案是

 <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"/>

第二种解决方案

      <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"/>