WPF - How to create image button with template

I am trying to create a button which has 3 images: a Normal image, a Pressed image and a Disabled image (I will use these for creating up/down arrow buttons).

I believe the correct approach would be to derive from Button and use a Template and set triggers to change the image. I have 3 dependency properties, one for each image.

The images would be .png and have transparent backgrounds (as they are not rectangular).

I am looking for something like CBitmapButton in MFC.


You won't need dependency properties because you are inheriting from Button. You already have the IsPressed and IsEnabled properties. In fact, this is all you need:

<Button x:Class="TestWpfApplication.ThreeStateImageButton"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Button.Template>
      <ControlTemplate TargetType="{x:Type Button}">
         <Grid>
            <Image Name="Normal" Source="Resources/Normal.png"/>
            <Image Name="Pressed" Source="Resources/Pressed.png" Visibility="Hidden"/>
            <Image Name="Disabled" Source="Resources/Disabled.png" Visibility="Hidden"/>
         </Grid>
         <ControlTemplate.Triggers>
            <Trigger Property="IsPressed" Value="True">
               <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
               <Setter TargetName="Pressed" Property="Visibility" Value="Visible"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
               <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
               <Setter TargetName="Disabled" Property="Visibility" Value="Visible"/>
            </Trigger>
         </ControlTemplate.Triggers>
      </ControlTemplate>
   </Button.Template>
</Button>

With your UserControl code-behind file:

public partial class ThreeStateImageButton : Button
{
   public ThreeStateImageButton()
   {
      InitializeComponent();
   }
}

I have provided an alternative to this solution, its not quite as light weight but it offers much greater re-usability.

WPF TriState Image Button