2014-01-06 2 views
1

У меня есть кнопка, и я хочу изменить цвет фона кнопки. но когда я устанавливаю фона свойство цвета, как синий:Изменение backgorund кнопки в wpf, когда она имеет фокус

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

и когда кнопка имеет фокус, цвет меняется в белом и мой цвет.

Как я могу установить этот белый цвет на другой цвет?

+0

проверки buttonstate свойство .И добавить триггер на основе состояния –

+0

Попробуйте стиль, приведенный в следующей ссылке , http://stackoverflow.com/questions/20669013/eliminating-highlight-on-button-click-xaml/20681609#20681609 – Boopesh

ответ

4

Я считаю, что ваша проблема вызвана по умолчанию 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> 
+0

ваш код вызывает эту ошибку: «Не удается найти статический член» ContentProperty 'на типе «Управление» – mohammad

+0

Извините, я еще не совсем в правильном режиме работы. Я забыл установить существенное свойство TargetType, а также полностью забыл «Trigger». Там все работает и работает. – Sheridan

+0

@Sheridan Как мы можем изменить стиль сфокусированной кнопки по всему миру? Я имею в виду, если какая-либо кнопка во всем проекте будет сфокусирована, станет синей. http://stackoverflow.com/questions/33248824/how-to-change-the-styling-of-the-dotted-line-around-focused-button-globally-in-w#33248824 –

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

не работает !! –

+0

Сообщено [в другом месте] (http://stackoverflow.com/a/28348044/2670182), которое изменяется с тех пор, как в Windows 8 произошла ошибка:/ –

Смежные вопросы