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"/>
       <Trigger Property="IsMouseOver" Value="true">
        <Setter Property="Source" TargetName="image" Value="prev_hover.png"/>
       <Trigger Property="IsPressed" Value="true">
        <Setter Property="Source" TargetName="image" Value="prev_down.png"/>



Comments (3)

  1. wkempf says:

    I don’t understand "Okay, so it’s not very general in that it hardcodes the behavior for the specific button, but it was really cheap to do."  You didn’t show the full code, so I can only guess.  I’m guessing your ControlTemplate is hard coded as a property on your button, and that’s why you gave that quote.  If this assumption is correct, then the answer is to use a Style to apply the control template!

    On the other hand, if it’s that the images are hard coded, you could get around that through data binding, though with out a custom control you’d have to get creative since you don’t have dependency properties to bind to at the "outer" Button level.  One creative solution would be to bind the button’s content to an object with your various properties that the template would then bind to the individual components here.  Hope that made some sense.

  2. ericgu says:


    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…

  3. anothr user says:

    One new subscriber from Anothr Alerts

Skip to main content