C# WPF Data Binding and Triggers MouseOvers

You are writing a C# WPF program and you want a button to change colour when the user runs the mouse over it. How do you do that? You can use triggers. Every control has a Triggers property that you can use to define triggers directly on that control. In this example, the left button, when the mouse is over it will change its font colour to red and make the font bold.


Below is the XAML code for this example.

<Window x:Class="TriggersMike.MainWindow"
        Title="MainWindow" Height="150" Width="360">
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="29,32,0,0" VerticalAlignment="Top" Width="75">
                <Style TargetType="Button">
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="Foreground" Value="Red"></Setter>
                            <Setter Property="FontWeight" Value="Bold"></Setter>
        <Button x:Name="button1" Content="Button1" HorizontalAlignment="Left" Margin="225,32,0,0" VerticalAlignment="Top" Width="75">
                <Style TargetType="Button">
                    <Setter Property="Foreground">
                            <SolidColorBrush Color="Purple"/>
        <Label x:Name="label" Content="Triggers, Styles, IsMouseOver" HorizontalAlignment="Left" Height="34" Margin="10,75,0,0" VerticalAlignment="Top" Width="318"/>

You can find out information about controls and their state. Other properties include IsFocused, to determine whether a control has focus; IsHitTestVisible, which indicates whether it is possible to click on a control (it is not obscured by controls further up the stacking order); and IsPressed, which indicates whether a button is pressed. The last of these only applies to buttons that inherit from ButtonBase, whereas the other are available on all controls.


Property triggers are just one of three kinds of trigger supported by WPF. A data trigger is a form of property trigger that works for all .NET properties, not just dependency properties. (The Setters inside a data trigger are still restricted to setting dependency properties, however.) An event trigger enables you to declaratively specify actions to take when a routed event is raised. Event triggers always involve working with animations or sounds.

Data triggers are discussed on pages 427-430 in the book WPF 4.5 Unleashed.

Leave a comment

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