2014-09-24 110 views
1

我已经编写了此代码,用于将文本插入到Button中。所以我有这样的:WPF如何在鼠标位于按钮上时更改背景图片

<Button Style="{StaticResource TransparentButton}" 
     Grid.Column="0" 
     Grid.Row="0" 
     Command="{Binding Path=MovePreviousCommand}" 
     Width="150"> 
    <Button.Content> 
     <StackPanel Orientation="Horizontal"> 
      <Grid> 
       <Image Source="./Resources/Images/bottone_indietro.png" Width="130"/> 
       <Label Content="{x:Static res:Strings.GestoreWizardView_Button_MovePrevious}" 
         HorizontalAlignment="Center" VerticalAlignment="Center" 
         Margin="48,10,26,8" Style="{StaticResource LabelStyleButton}" 
         /> 
      </Grid> 

     </StackPanel> 
    </Button.Content> 
</Button> 

这是一个样式按钮

<Style TargetType="Button" x:Key="TransparentButton"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="Button"> 
       <Border Background="Transparent"> 
        <ContentPresenter/> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

现在我想改变背景图像时,鼠标移动到按钮。

我们可以帮我吗?

最好的调节器。

+0

它是按钮或整个窗口的背景吗? – ZoomVirus 2014-09-24 14:53:05

+0

是按钮 – bircastri 2014-09-24 14:53:48

回答

2

这应该工作提供您想要的图像是在资源文件夹内。

<Style x:Key="TransparentButton" TargetType="Button"> 
    <Setter Property="OverridesDefaultStyle" Value="True"/> 
    <Setter Property="Margin" Value="5"/> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="Button"> 
       <Border Name="border" 
        BorderThickness="0" 
        Background="{TemplateBinding Background}"> 
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> 
       </Border> 
       <ControlTemplate.Triggers> 
        <Trigger Property="IsMouseOver" Value="True"> 
         <Setter Property="Background" TargetName="border"> 
         <Setter.Value> 
          <ImageBrush ImageSource="Resources/image.jpg" /> 
         </Setter.Value> 
        </Setter> 
       </Trigger> 
       </ControlTemplate.Triggers> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 
+0

的背景我尝试使用你的代码和它的作品,但背景图像是在默认背景下图片,我认为这个方法在按钮上插入背景图片是错误的“” – bircastri 2014-09-24 15:32:12

+0

确保图像的构建操作设置为资源。 – ZoomVirus 2014-09-24 15:51:29

+0

这里的问题是你设置了按钮背景,而原始图像被添加为内容。它需要匹配,无论是作为背景还是作为内容。 – 2014-09-24 15:58:11

0

为了保持其紧凑:

<Image Width="130" > 
    <Image.Style> 
     <Style TargetType="{x:Type Image}"> 
      <Setter Property="Source" Value="./Resources/Images/bottone_indietro.png"/> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=Button}}" Value="True"> 
        <Setter Property="Source" Value="./Resources/Images/bottone_indietro_altro.png"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </Image.Style> 
</Image> 

我得到一个无害的设计时异常(运行正常),因为按钮的祖先是在运行时才能检测。如果这是一个问题,你可以尝试this