2016-02-08 4 views
1

Так что все, что я пытаюсь сделать, это изменить цвет кнопки при нажатии, но я потратил хорошее количество на ошибки и не нашел ничего полезного. Поймите, я совершенно новый для сообщества Visual Studio 2015.Измените переднюю часть кнопки при нажатии

Существует, по-видимому, много способов сделать это, используя кисти или сплошную краску или конверсию.

Просьба указать использование и ссылки необходимо

вот моя кнопка:

<Button x:Name="CastButton" 
     Click="CastButton_Click" 
     HorizontalAlignment="Right" 
     VerticalAlignment="Bottom" 
     Margin="0,0,35,10" 
     FontFamily="Segoe MDL2 Assets" 
     FontSize="24" 
     Foreground="AliceBlue" 
     Content="&#xE72D;"> 
</Button> 

ответ

0

Если вы хотите изменить цвет переднего плана при нажатии на кнопку, вы должны изменить стиль из ваш контроль. Щелкните правой кнопкой мыши на кнопке в проектировщиком окне, затем Edit Template ->Редактирование Копировать - это должно создать копию шаблона по умолчанию в ресурсах, он должен выглядеть следующим образом:

<Page.Resources> 
    <Style x:Key="MyButtonStyle" TargetType="Button"> 
     <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/> 
     <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/> 
     <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundTransparentBrush}"/> 
     <Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}"/> 
     <Setter Property="Padding" Value="8,4,8,4"/> 
     <Setter Property="HorizontalAlignment" Value="Left"/> 
     <Setter Property="VerticalAlignment" Value="Center"/> 
     <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/> 
     <Setter Property="FontWeight" Value="Normal"/> 
     <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/> 
     <Setter Property="UseSystemFocusVisuals" Value="True"/> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Button"> 
        <Grid x:Name="RootGrid" Background="{TemplateBinding Background}"> 
         <VisualStateManager.VisualStateGroups> 
          <VisualStateGroup x:Name="CommonStates"> 
           <VisualState x:Name="Normal"> 
            <Storyboard> 
             <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/> 
            </Storyboard> 
           </VisualState> 
           <VisualState x:Name="PointerOver"> 
            <Storyboard> 
             <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter"> 
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseMediumLowBrush}"/> 
             </ObjectAnimationUsingKeyFrames> 
             <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter"> 
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/> 
             </ObjectAnimationUsingKeyFrames> 
             <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/> 
            </Storyboard> 
           </VisualState> 
           <VisualState x:Name="Pressed"> 
            <Storyboard> 
             <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid"> 
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseMediumLowBrush}"/> 
             </ObjectAnimationUsingKeyFrames> 
             <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter"> 
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}"/> 
             </ObjectAnimationUsingKeyFrames> 

             <!--Here is the change of foreground when pressed--> 
             <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter"> 
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/> 
             </ObjectAnimationUsingKeyFrames> 

             <PointerDownThemeAnimation Storyboard.TargetName="RootGrid"/> 
            </Storyboard> 
           </VisualState> 
           <VisualState x:Name="Disabled"> 
            <Storyboard> 
             <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid"> 
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/> 
             </ObjectAnimationUsingKeyFrames> 
             <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter"> 
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}"/> 
             </ObjectAnimationUsingKeyFrames> 
             <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter"> 
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}"/> 
             </ObjectAnimationUsingKeyFrames> 
            </Storyboard> 
           </VisualState> 
          </VisualStateGroup> 
         </VisualStateManager.VisualStateGroups> 
         <ContentPresenter x:Name="ContentPresenter" AutomationProperties.AccessibilityView="Raw" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/> 
        </Grid> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Page.Resources> 

Узнаете цвета этой кнопки изменяются визуальным менеджером состояний в зависимости от текущего состояния. В прессованной состояния вы найдете это:

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter"> 
    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/> 
</ObjectAnimationUsingKeyFrames> 

Это означает, что независимо от того, вы установили на передний план, при нажатии, визуальное состояние менеджер всегда будет менять цвет кнопки на SystemControlHighlightBaseHighBrush. Конечно, вы можете изменить это значение в стиле. Затем примените его только к вашей кнопке:

<Button Content="Button with style" Style="{StaticResource MyButtonStyle}"/> 
+0

ОК, я имел в виду, что изменение цвета будет переключаться при каждом нажатии или выключении. Мне удалось найти дешевый способ изменить цвет с помощью 'собственной пустоты CastButton_Click (отправитель объекта, RoutedEventArgs е) { CastButton.Foreground = новый Windows.UI.Xaml.Media.SolidColorBrush (Windows.UI.Color. FromArgb (0xff, 0xff, 0x90, 0x90)); } ' – John

+0

@John Если вы хотите кнопку включения/выключения, то почему бы не использовать [ToggleButton] (https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml. controls.primitives.togglebutton)? – Romasz

+0

, потому что я новичок и вам нужно исследовать больше ... :( – John

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