2

我有一个带有图像的按钮,如下所示:

<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>

我想应用一些鼠标悬停效果来识别按钮是可点击/可聚焦的。我尝试按如下方式添加触发器,但它不起作用:

<ControlTemplate.Triggers>
  <Trigger Property="IsMouseOver" Value="True"> 
    <Setter Property="Background" Value="Black" /> 
  </Trigger>
</ControlTemplate.Triggers>

它不工作。我需要做什么?请帮帮我。

4

1 回答 1

8

您的控制模板此时包含一个图像,因此您无法更改背景(通过触发器)。如果您想添加背景更改,则需要扩展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 simple example of how you can utilize the trigger you've shown above. All this does is add a Grid under the image and a Margin to the image so that part of the Grid is visible. It then uses the Target property of the Setter to assign the Background of the Grid when the user hovers over the button. You can certainly do much more with your ControlTemplate to provide other types of visual cues, but hopefully this will get you started.

于 2012-08-04T13:28:02.540 回答