我们如何在具有透明背景的MouseOver上显示WPF按钮内容

时间:2014-07-21 10:44:26

标签: wpf xaml

我希望WPF按钮在鼠标上的行为只有我想要显示按钮的内容(它的图像)  而且在鼠标悬停时我希望背景为透明+无边框。 按钮内容是一个图像,我给出50像素的填充。所以鼠标在按钮上接近50px,我可以看到按钮内容。 我使用的xaml是

  <Button  Style="{StaticResource FadeOutButton}" Padding="50" Opacity="0" >                        
                    <Image Source="Images\myimage.JPG"></Image>

  <Style x:Key="FadeOutButton" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Transparent"/>            
        <Style.Triggers>
            <EventTrigger RoutedEvent="Control.MouseEnter">
                <BeginStoryboard>
                    <Storyboard >
                        <DoubleAnimation Duration="0:0:1" To="1" Storyboard.TargetProperty="Opacity"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
            <EventTrigger RoutedEvent="Control.MouseLeave">
                <BeginStoryboard>
                    <Storyboard >
                        <DoubleAnimation Duration="0:0:1" To="0" Storyboard.TargetProperty="Opacity"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>

除了当前效果

之外,还需要添加什么才能使鼠标悬停时背景透明

1 个答案:

答案 0 :(得分:0)

试试这个

<Window.Resources>
    <Style x:Key="FadeOutButton" TargetType="{x:Type Button}">
        <Style.Resources>
            <Storyboard x:Key="MouseOverAnimation" >
                <DoubleAnimation Duration="0:0:1" To="1" Storyboard.TargetProperty="Opacity"/>
            </Storyboard>
            <Storyboard x:Key="MouseOutAnimation">
                <DoubleAnimation Duration="0:0:1" To="0" Storyboard.TargetProperty="Opacity"/>
            </Storyboard>
        </Style.Resources>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="Transparent" >
                        <ContentPresenter Margin="{TemplateBinding Padding}"  HorizontalAlignment="Center" Content="{TemplateBinding Content}" VerticalAlignment="Center"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Transparent"/>
                <Trigger.EnterActions>
                    <BeginStoryboard Storyboard="{StaticResource MouseOverAnimation}" />
                </Trigger.EnterActions>
                <Trigger.ExitActions>
                    <BeginStoryboard Storyboard="{StaticResource MouseOutAnimation}" />
                </Trigger.ExitActions>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<Button  Style="{StaticResource FadeOutButton}" Padding="50" Opacity="0" >
    <Image Source="Screenshot_3.png"></Image>
</Button>