如何在鼠标悬停时更改按钮的背景

时间:2014-08-22 22:59:16

标签: c# wpf button background mouseover

在下面的代码中,我想在鼠标悬停时将蓝色图像背景按钮更改为绿色图像按钮。

我的XAML代码如下,但鼠标悬停在按钮上没有任何反应。 NextButton.png是原始按钮,nextGreen.png应该是鼠标悬停的背景。

问题出在哪里?

<Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
        Content=""
        HorizontalAlignment="Right"
        Margin="0,0,0.2,0"
        VerticalAlignment="Bottom"
        Width="50"
        Height="100"
        Grid.Column="1"
        Click="Next_Click">
    <Button.Background>
        <ImageBrush ImageSource="NextButton.png" />
    </Button.Background>
    <Button.Template>
        <ControlTemplate>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver"
                         Value="True">
                    <Setter Property="Background">
                        <Setter.Value>
                            <ImageBrush ImageSource="nextGreen.png" />
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </ControlTemplate.Triggers>
            <StackPanel>
                <StackPanel.Background>
                    <ImageBrush ImageSource="Nextbutton.png"/>
                </StackPanel.Background>
            </StackPanel>
        </ControlTemplate>
    </Button.Template>
</Button>

1 个答案:

答案 0 :(得分:0)

您可以设置按钮的背景,然后覆盖Template,以便Button.Background永远不显示。您应该删除Button.Background,然后在StackPanel中为Template命名,以便您可以更改Trigger中的背景。

 <Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Content="" HorizontalAlignment="Right" Margin="0,0,0.2,0" VerticalAlignment="Bottom" Width="50" Height="100" Grid.Column="1" Click="Next_Click">
   <Button.Template>
        <ControlTemplate>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" TargetName="root">
                        <Setter.Value>
                            <ImageBrush ImageSource="nextGreen.png" />
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </ControlTemplate.Triggers>
            <StackPanel x:Name="root">
                <StackPanel.Background>
                    <ImageBrush ImageSource="Nextbutton.png"/>
                </StackPanel.Background>
            </StackPanel>
        </ControlTemplate>
    </Button.Template>
</Button>