wpf 在 XAML 中为带有图像的按钮添加鼠标悬停效果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11808955/
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
adding mouseover effect to a button with Image in XAML
提问by deathrace
I am having a button with Image on it as follows:
我有一个带有图像的按钮,如下所示:
<Button Width="22" Height="22" Command="{Binding PreviousCommand}">
<Button.Template>
<ControlTemplate>
<Image Source="C:\Users\abcdef\Desktop\Slide-To-Left-Arrow-24.png"></Image>
</ControlTemplate>
</Button.Template>
<Button.InputBindings>
<KeyBinding Key="Up" Command="{Binding PreviousCommand}" Modifiers="Alt+Shift" />
</Button.InputBindings>
</Button>
I want to apply some mouse over effect to recognise button is clickable/focusable. I tried adding trigger as follows but its not working:
我想应用一些鼠标悬停效果来识别按钮是可点击/可聚焦的。我尝试按如下方式添加触发器但它不起作用:
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
Its not working. what I need to do? please help me out.
它不工作。我需要做什么?请帮帮我。
回答by Brian S
Your control template consists onlyof an Image at this point, so there is nothing that you can change the background on (through your trigger). If you'd like to add a background change, you'll need to expand your ControlTemplatea little. Try something like this:
此时您的控制模板仅包含一个图像,因此您无法更改背景(通过触发器)。如果您想添加背景更改,则需要ControlTemplate稍微扩展一下。尝试这样的事情:
<Button.Template>
<ControlTemplate>
<Grid x:Name="bg">
<Image Margin="4" Source="C:\Users\dheeraj.dilip.awale\Desktop\Slide-To-Left-Arrow-24.png"></Image>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Target="bg" Property="Background" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
This is just a very simpleexample of how you can utilize the trigger you've shown above. All this does is add a Gridunder the image and a Marginto the image so that part of the Gridis visible. It then uses the Targetproperty of the Setterto assign the Backgroundof the Gridwhen the user hovers over the button. You can certainly do much more with your ControlTemplateto provide other types of visual cues, but hopefully this will get you started.
这只是一个非常简单的示例,说明如何使用上面显示的触发器。所有这一切都是Grid在图像下方添加 a并在图像上添加 aMargin以便部分Grid可见。然后,当用户将鼠标悬停在按钮上时,它会使用 的Target属性Setter来分配 的。你当然可以做更多的事情来提供其他类型的视觉提示,但希望这能让你开始。BackgroundGridControlTemplate

