当鼠标悬停在按钮上时 WPF 更改图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17996887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF change Image when mouse hover on button
提问by Abanoub
I'm trying to change the image when mouse is over a button, but it's not working here is what am trying to do :
当鼠标悬停在按钮上时,我正在尝试更改图像,但它在这里不起作用,这正是我想要做的:
<Button x:Name="Play" Content="" ClickMode="Press" BorderThickness="0" UseLayoutRounding="True" Height="120" Width="224">
<Button.Background>
<ImageBrush ImageSource="Resources/Play 1.gif"/>
</Button.Background>
<Button.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="ImageBrush.ImageSource" Value="Resources/Play 2.gif"></Setter>
</Trigger>
</Button.Triggers>
</Button>
But this gives me this error : Triggers collection members must be of type EventTrigger.
但这给了我这个错误: Triggers collection members must be of type EventTrigger.
How would I make it work?
我将如何使它工作?
回答by Chris Mantle
It's correct - you can only put EventTriggers in there. You need to move your Trigger into the button's Style:
这是正确的 - 您只能将 EventTriggers 放在那里。您需要将您的触发器移动到按钮的样式中:
<Button x:Name="Play" Content="" ClickMode="Press" BorderThickness="0" UseLayoutRounding="True" Height="120" Width="224">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="..\Resources\Play 1.gif"/>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="..\Resources\Play 2.gif"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Something like that, I think (haven't tested it).
类似的东西,我想(还没有测试过)。
EDIT: This switches between the correct images, but it doesn't work correctly (it starts off with Play 1.gif, transitions to Play 2.gif, but then transitions to the button's underlying colour). I think you'll have to override the button's ControlTemplateto prevent this from happening, as suggested in the comments.
编辑:这在正确的图像之间切换,但它不能正常工作(它从播放 1.gif 开始,过渡到播放 2.gif,然后过渡到按钮的底层颜色)。我认为您必须ControlTemplate按照评论中的建议覆盖按钮以防止发生这种情况。

