77

I want the border to turn green when the mouse is over it and then to return to blue when the mouse is no longer over the border.

I attempted this without any luck:

<Border 
    Name="ClearButtonBorder" 
    Grid.Column="1" 
    CornerRadius="0,3,3,0" 
    Background="Blue">
    <Border.Triggers>
        <Trigger Property="Border.IsMouseOver" Value="True">
            <Setter Property="Border.Background" Value="Green" />
        </Trigger>
        <Trigger Property="Border.IsMouseOver" Value="False">
            <Setter Property="Border.Background" Value="Blue" />
        </Trigger>
    </Border.Triggers>
    <TextBlock 
        HorizontalAlignment="Center" 
        VerticalAlignment="Center" 
        Text="X" />
</Border>

How can one set a trigger or events for MouseOver?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Boris
  • 9,986
  • 34
  • 110
  • 147

1 Answers1

152

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Jan-Wiebe
  • 61
  • 2
  • 11
Grokys
  • 16,228
  • 14
  • 69
  • 101
  • 2
    Thank you for your answer. Now I know how it's done. Still, the reason why it has to be implemented like that remains illogical to me. But that's OK, I guess. :) – Boris Mar 05 '10 at 19:11
  • Yes, I agree it is illoigcal. As I say, seems to be a bug/omission from WPF. – Grokys Mar 06 '10 at 14:21
  • 6
    I disagree that it's either a bug or an omission. In WPF there is an explicit rule set defining property value precedence. http://msdn.microsoft.com/en-us/library/ms743230.aspx – Andrew Shepherd May 30 '14 at 02:20
  • 3
    The blog post's link is dead – franssu Nov 17 '14 at 13:41
  • 2
    The link is dead, but https://msdn.microsoft.com/en-us/library/ms743230%28v=vs.100%29.aspx is not. – PScr Sep 28 '15 at 10:27
  • Interestingly this didn't work for me on a `CheckBox` but wrapping a `Border` around it helped. – craftworkgames Mar 16 '16 at 00:03