Dela via


Hacky way of doing changing bitmaps on a button in WPF

I came up with a hacky way of doing "hover" and "press" buttons in WPF recently. There are a couple of nice examples on the web, but I was looking for a way to do it purely through XAML. If there's a nicer way to do it through XAML (or if there are big drawbacks to this approach) please let me know.

So, here's what I did.

  1. For the button, create a button template (very easy to do in blend...) that has an image in it, and hard-code that image to use the default bitmap. I also hardcoded the size to the image size.
  2. Add triggers for the IsMouseOver and IsPressed events to change the image to the appropriate hover or pressed bitmaps
  3. Apply the template to the button.

Okay, so it's not very general in that it hardcodes the behavior for the specific button, but it was really cheap to do.

 XAML looks something like this: 

     <ControlTemplate TargetType="{x:Type Button}">
     
       <Border x:Name="Border" Padding="{TemplateBinding Padding}" VerticalAlignment="Stretch" BorderThickness="2,2,2,2" CornerRadius="5,5,5,5">
        <Image HorizontalAlignment="Right" x:Name="image" Width="24" Height="26" Source="prev_rest.png"/>
       </Border>
     
      <ControlTemplate.Triggers>
       <Trigger Property="IsMouseOver" Value="true">
        <Setter Property="Source" TargetName="image" Value="prev_hover.png"/>
       </Trigger>
       <Trigger Property="IsPressed" Value="true">
        <Setter Property="Source" TargetName="image" Value="prev_down.png"/>
       </Trigger>
      </ControlTemplate.Triggers>
     </ControlTemplate>

Comments

  • Anonymous
    April 11, 2007
    The comment has been removed

  • Anonymous
    April 11, 2007
    wkempf, The template is wrapped in a named style, which is then applied to the button. My question was whether there was an easier way to get the behavior... I have seen an alternate version that uses a class to hold the URLs and then data binds to that, but that was more work...

  • Anonymous
    April 14, 2007
    One new subscriber from Anothr Alerts