Style the MouseOver on a Silverlight/WPF button

mattruma picture mattruma · Mar 8, 2010 · Viewed 40.6k times · Source

Struggling with styling the mouse over for a button ... I have managed to style the button (solid red), but I would like for it to change to solid black whenever a mouse over occurs. I am new to XAML, and I can see that it wants some type of story board/animation ... not sure exactly how to do this.

Any help would be greatly appreciated.

Answer

Ben Von Handorf picture Ben Von Handorf · Mar 8, 2010

This is different from WPF to Silverlight. In WPF, the answer from Rob is correct.

In Silverlight, this won't work. Silverlight uses the VisualStateManager instead of triggers. The code for this is more complex, but some people feel that this is better. You wind up having to create a control template in your style. (For information on defining the control template, see This Article. The easiest way to create a similar ControlTemplate is to use Expression Blend, which has a function to extract the existing template in full for you.)

In the control template, define the VisualState you care about and what you want to happen.

<VisualStateGroup x:Name="CommonStateGroup">
    <VisualState x:Name="MouseOverState">
        <Storyboard>
            <ColorAnimation Storyboard.TargetName="TopmostElementOfTheTemplate" 
                                       Storyboard.TargetProperty="Foreground" 
                                       To="Black"
                                       Duration="00:00:00" >
            </ColorAnimation>
        </Storyboard>
    </VisualState>
</VisualStateGroup>
...

It is important to specify the default foreground color in the style as well, as Rob did above. If you specify it on the control instead it will override values from the style.

Note that it is possible to get the VisualStateManager out of the WPF Toolkit to have a similar solution in WPF.