views:

640

answers:

1

How to set MouseOver event/trigger for border in XAML? 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. Why can't I just use the following code:

<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>

I really don't get these triggers and styles in WPF. It is such a drag not to be able to achieve something simple as this.. Please provide the solution for me and help me understand what the heck is wrong with my code? Thanks a bunch.

+2  A: 

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.

Groky
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
Yes, I agree it is illoigcal. As I say, seems to be a bug/omission from WPF.
Groky