我如何在Label中使用isPressed?

时间:2014-10-28 02:03:33

标签: c# wpf

这是我的代码的一部分,我已经在谷歌搜索它,但没有人知道我的意思。

 <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Width="30" Height="30" Content="" FontFamily="FontAwesome" HorizontalAlignment="Right" VerticalAlignment="Center">
                <Label.Style>
                    <Style TargetType="{x:Type Label}">
                        <Style.Triggers>
                            <Trigger Property="Label.IsMouseOver" Value="True">
                                <Setter Property="Label.Background" Value="Yellow" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Label.Style>
            </Label>

1 个答案:

答案 0 :(得分:1)

在这种情况下,您可以尝试使用EventTrigger。如果当然更长,但它是使用纯标准XAML(不是任何自定义)的最简单方法:

<Label HorizontalContentAlignment="Center" VerticalContentAlignment="Center" 
       Width="30" Height="30" Content="Clgt?" FontFamily="FontAwesome" 
       HorizontalAlignment="Right" VerticalAlignment="Center">
     <Label.Style>
        <Style TargetType="{x:Type Label}">
            <Style.Triggers>
                <EventTrigger RoutedEvent="MouseLeftButtonDown">
                   <BeginStoryboard>
                      <Storyboard>
                          <ColorAnimation To="Yellow" Duration="0" 
                            Storyboard.TargetProperty="Background.Color"/>
                      </Storyboard>
                   </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="MouseLeftButtonUp">
                   <BeginStoryboard>
                      <Storyboard>
                          <ColorAnimation To="Transparent" Duration="0" 
                            Storyboard.TargetProperty="Background.Color"/>
                      </Storyboard>
                   </BeginStoryboard>                    
                </EventTrigger>
             </Style.Triggers>
         </Style>
      </Label.Style>
 </Label>

RemoveStoryboard这样的情况下使用MouseLeftButtonUp行动会更好:

<Style.Triggers>
    <EventTrigger RoutedEvent="MouseLeftButtonDown">
        <BeginStoryboard Name="bg">
           <Storyboard>
              <ColorAnimation To="Yellow" Duration="0" 
                              Storyboard.TargetProperty="Background.Color"/>
           </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
    <EventTrigger RoutedEvent="MouseLeftButtonUp">
         <RemoveStoryboard BeginStoryboardName="bg"/>
    </EventTrigger>
</Style.Triggers>