WPF在按钮上设置边框以淡入和淡出

时间:2018-09-20 14:11:53

标签: wpf xaml mahapps.metro

我正在尝试使按钮边框淡入和淡出。我有效果,但是将它应用于整个按钮而不是边框​​。

App.xamml:

<Style x:Key="PassiveGlow"     
  BasedOn="{StaticResource GlowingButton}"  
  TargetType="{x:Type Button}">   

   <Style.Triggers>
    <Trigger Property="IsMouseOver" Value="False">
      <Trigger.EnterActions>
        <BeginStoryboard>
        <Storyboard>
          <DoubleAnimation 
            Storyboard.TargetProperty="Opacity"
            From="1.0" To="0.0" Duration="0:0:5" 
            AutoReverse="True" RepeatBehavior="Forever" />
        </Storyboard>
         </BeginStoryboard>
      </Trigger.EnterActions>
    </Trigger>
 </Style.Triggers>
</Style>

按钮XAML:

<Button x:Name="LoginButton"
    Padding="5"
    HorizontalAlignment="Left"
    Margin="0,10,0,0"
    Width="100"
    Content="Login"
    ToolTipService.ShowDuration="20000"
    Click="PasswordButtonClick" TabIndex="2"
    Style="{DynamicResource PassiveGlow}">

1 个答案:

答案 0 :(得分:0)

您可以使用以下描述的样式实现此效果:

<Style x:Key="PassiveGlow"  TargetType="{x:Type Button}">
       <Setter Property="BorderBrush" Value="Red" />
       <Setter Property="BorderThickness" Value="3" />
        <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" >
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
       <Style.Triggers>
          <EventTrigger RoutedEvent="Button.Loaded">
          <BeginStoryboard>
              <Storyboard>
                <DoubleAnimation 
                  Storyboard.TargetProperty="BorderBrush.Opacity"
                  From="1.0" To="0.0" Duration="0:0:2" 
                  AutoReverse="True" RepeatBehavior="Forever"/>
              </Storyboard>
               </BeginStoryboard>
         </EventTrigger>       
     </Style.Triggers>
    </Style>

此动画将在Button加载后立即开始,并且将一直重复,因为我已经使用Button.Loaded作为RoutedEvent并将RepeatBehavior设置为Forever。如果希望此动画仅在鼠标第一次进入按钮时才运行,则可以将RoutedEvent更改为Button.MouseEnter。另外,请注意,在尝试该示例时,我没有可用的材质样式,因此我为按钮添加了新的ControlTemplate并从样式中删除了BasedOn =“ {StaticResource GlowingButton}”部分。

要使用阴影效果代替边框:

  1. 添加样式设置器,将BorderThickness值设置为0。
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Effect">
        <Setter.Value>
           <DropShadowEffect  ShadowDepth="5" Color="#7D00FE"/>
        </Setter.Value>
    </Setter>
  1. 编辑情节提要以目标Effect.ShadowDepth属性为目标
  <Storyboard>
      <DoubleAnimation 
        Storyboard.TargetProperty="Effect.ShadowDepth"
        From="3.0" To="0.0" Duration="0:0:2" 
        AutoReverse="True" RepeatBehavior="Forever"/>
  </Storyboard>