When i first decided to write this blog entry i took a rather angry tone. I was trying to achieve a image rollover effect that is common place in the web world. But i was failing badly in the world of WPF. As hard as i tried googling, it seamed that nobody knew how to do it, or if they did they didn’t take the time to let the rest of us know.
A few weeks after i decided to have a second attempt and what do you know, i found it pretty simple. So here is how to create WPF Rollover image buttons.
The way i finally 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.
Heres 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 code 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 color which is just as easy.
