Can Of Code

WPF – How To Create Image Rollover Buttons

Here is how to create WPF Rollover image buttons.

The way I achieved the rollover images is pretty simple, I create a ControlTemplate then add a Trigger  to change the background when the user moves the mouse over the button.

Here is the sample code:

<Window.Resources>
   <ImageBrush x:Key="RO1"
             ImageSource="/HTMLRolloverWPF;component/Images/4.ico" />
   <ImageBrush x:Key="RO2"
             ImageSource="/HTMLRolloverWPF;component/Images/3.ico" />

        <ControlTemplate TargetType="Button" x:Key="imageRoll">
            <Grid Name="gridy" Background="{StaticResource RO1}">
                <ContentPresenter  />
            </Grid>

            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="gridy" Property="Background"
                                                Value="{StaticResource RO2}" />
                </Trigger>
            </ControlTemplate.Triggers>

        </ControlTemplate>
</Window.Resources>
<Grid>
   <Button Content="Button"  Template="{StaticResource imageRoll}" />
</Grid>

The first part of that XAML is where I create a ControlTemplate. You can place the ControlTemplate in
which ever Resources collection that is most relevant. I have also set the target type and given the whole thing a key.

The Next chunk of code is where we add a Grid to the ControlTempalte. We will use the grid to display the background. We set the background of the grid to a imagebrush resource we defined earlier in the resource collection.

Now for the bit that does all the work, the Trigger!  We set a trigger to activate when the “IsMouseOver” Property is True. Then we use a setter to change the background of the grid to our rollover ImageBrush which in the example is called RO2.

Its as simple as that!  If you don’t want to do a image rollover you can just change the background to a different colour which is just as easy.

2 thoughts on “WPF – How To Create Image Rollover Buttons

  1. Pankaj Nikam says:

    The link is broken. Please give me the udpated link.

    1. josh says:

      Unfortunately I no longer have the files. the code example should contain everything that’s needed.

Leave a Reply

Your email address will not be published. Required fields are marked *